首页 > 解决方案 > 在散点图的框中选择点

问题描述

我必须从框中的散点图中选择值。所以基本上我需要盒子内所有点的值

N = 500
x = np.random.rand(N) * 2
y = np.random.rand(N) * 2.5
area = np.pi*3
colors = (0,0,0)

fig = plt.figure()
ax1 = fig.add_subplot(111)

plt.scatter(x, y, s=area, alpha=0.5)
plt.xlim(0.0, 2.0)
plt.ylim(0.0, 2.5)
plt.plot([0.7,1.0], [1.15,1.45], 'k--', lw=2)
plt.plot([0.3,0.6], [1.65,1.95], 'k--', lw=2)
    
plt.plot([0.7,0.3], [1.15, 1.65], 'k--', lw=2)
plt.plot([1.0, 0.6], [1.45, 1.95], 'k--', lw=2)

plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')

在此处输入图像描述

这类似于我之前的一个问题 Selecting points within a region of a scatter plot

但是我在考虑如何为盒子而不是多边形做这件事时遇到了麻烦。我之前尝试过执行我的步骤,但是当我尝试为它们着色以表明我正确选择了该区域内的点时,着色不正确。任何帮助都是极好的!

标签: pythonmatplotlib

解决方案


您可以为凸多边形的每条边创建线方程。然后您可以将它们用作过滤器(如果点相反,您需要将其更改为)><

from matplotlib import pyplot as plt
import numpy as np

# line equation of the form ax+by+c = 0 through (x0,y0) and (x1,y1);
# ax+by+c < 0 for points left of the line
def get_line_eq(x0, x1, y0, y1):
    return y0 - y1, x1 - x0, x0 * y1 - x1 * y0

N = 500
x = np.random.rand(N) * 2
y = np.random.rand(N) * 2.5
area = 10

fig = plt.figure()
ax1 = fig.add_subplot(111)

plt.scatter(x, y, s=area, alpha=0.5)
plt.xlim(0.0, 2.0)
plt.ylim(0.0, 2.5)

pnts = [[0.7, 1.15], [1.0, 1.45], [0.6, 1.95], [0.3, 1.65]]
pnts = pnts + [pnts[0]] # repeat first point to create a closed polygon
pnts = np.array(pnts) # numpy arrays are easier to separate x and y coordinates
plt.plot(pnts[:, 0], pnts[:, 1], 'k--', lw=2)

equations = [get_line_eq(x0, x1, y0, y1) for (x0, y0), (x1, y1) in zip(pnts[:-1], pnts[1:])]
filter = np.all([a*x + b*y + c > 0 for a, b, c in equations], axis=0)

plt.scatter(x[filter], y[filter], s=20, color='red', alpha=0.5)

plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
# plt.gca().set_aspect('equal', 'box')  # show right angles
plt.show()

过滤平行四边形内的点

PS:plt.fill()创建一个填充多边形:

plt.fill(pnts[:, 0], pnts[:, 1], fc='yellow', alpha=0.5, ec='k', ls='--', lw=2, zorder=0)

推荐阅读