识别并计算用户定义的线段内的点
我正在尝试找出并计算那些位于用户定义的“楔形”选择中的数据点。这些数据点都有自己的ID号,并且是从一个CSV文件中加载的,而这个“楔形”只是一些画在图上的线。
下面是一个图的例子:
import matplotlib.pyplot as plt
x = ID['x']
y = ID['y']
plt.figure()
plt.scatter(x, y)
plt.plot([-1, -1, 2, 2, ], [4, 1, -2, 4], color='r', linewidth=1, linestyle='--')
plt.xlim(-4,4)
plt.ylim(-4,4)
plt.show()
示例图:http://i.imgur.com/UENwbks.png
我想要两个输出结果:
1) 一个包含所有在“楔形”内的ID(数据点)的列表
2) 所有ID(数据点)的数量,这个任务在完成第一个后就简单多了!
我最初的想法是类似这样的:
ID['x'] >= -1 and ID['x'] <= 2 and ???
其中 ??? 是楔形上方的区域(也许是一个线性方程?)。
任何帮助都非常感谢。
1 个回答
2
你可以定义一个路径,然后使用它的 contains_points 方法来检查某些点是否在这个路径内。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
x, y = np.random.random((2, 100))*8 - 4
points = np.column_stack([x, y])
verts = np.array([[-1, -1, 2, 2, ], [4, 1, -2, 4]]).T
path = mpath.Path(verts)
points_inside = points[path.contains_points(points)]
plt.figure()
plt.scatter(x, y)
plt.plot([-1, -1, 2, 2, ], [4, 1, -2, 4], color='r', linewidth=1, linestyle='--')
plt.scatter(points_inside[:,0], points_inside[:,1], c='r', s=50)
plt.xlim(-4,4)
plt.ylim(-4,4)
plt.show()