python - 在散点图的框中选择点
问题描述
我必须从框中的散点图中选择值。所以基本上我需要盒子内所有点的值
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
但是我在考虑如何为盒子而不是多边形做这件事时遇到了麻烦。我之前尝试过执行我的步骤,但是当我尝试为它们着色以表明我正确选择了该区域内的点时,着色不正确。任何帮助都是极好的!
解决方案
您可以为凸多边形的每条边创建线方程。然后您可以将它们用作过滤器(如果点相反,您需要将其更改为)>
:<
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)
推荐阅读
- javascript - combineLatest 运算符替代
- python - 使用pip命令不起作用,pip找不到python
- php - 使用打开模式的按钮创建光滑的滑块
- git - git push 后总是从命令行链接到 GitHub 拉取请求?
- scala - 将元组转换为具有默认值的案例类
- javascript - HTML 包含使用 ajax - 如何访问包含的文件元素?
- reporting-services - SSRS 表达式中的 LAST WHERE 子句
- php - 更改 WooCommerce 订单中管理员帐单地址字段的顺序
- java - 如何检测一加和小米设备和其他中文rom的andorid 9及更高版本中的BOOT_COMPLETED(api级别28+)
- string - 使用 PL/SQL 将字符串拆分为一行或多行