python - 有没有办法在 Python 中对一组 2D 坐标进行 bin 处理
问题描述
嘿,所以我有一个二维数组,x,y coordinates
格式为:[[x0,y0],[x1,y1],....,[xn,yn]]
。这些坐标位于一个大小为x_length
和的矩形内y_length
。我想将矩形分割成一组正方形,并找出每个正方形中有多少个坐标,如果这有任何意义的话。使用 2D 直方图函数 ( np.histogram2d()
) 我设法做了类似的事情,但它没有告诉我每个 bin 中的实际点数(这是我想要得到的)。我附上了二维直方图的示例以供参考。
在此处输入图像描述
解决方案
values, xbins, ybins = np.histogram2d(x=a[:,0], y=a[:,1])
将每个 bin 的实际点数给出为值. 请注意,许多 matplotlib 函数首先按 索引y
,因此您可能需要values.T
根据用例。
这是一个显示如何使用这些值的可视化。
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import numpy as np
x = np.linspace(-0.212, 0.233, 50)
y = x * 0.5 - 0.01
hist, xbins, ybins = np.histogram2d(x=x, y=y, bins=(np.arange(-0.25, 0.25001, 0.02), np.arange(-0.15, 0.15001, 0.02)))
fig, ax = plt.subplots(figsize=(11, 6))
for i in range(len(xbins) - 1):
for j in range(len(ybins) - 1):
text = ax.text((xbins[i] + xbins[i + 1]) / 2, (ybins[j] + ybins[j + 1]) / 2, f"{hist[i, j]:.0f}",
color='cornflowerblue', size=16, ha='center', va='center')
text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='white', alpha=0.6), path_effects.Normal()])
ax.plot(x, y, '-ro')
ax.set_xlim(xbins.min(), xbins.max())
ax.set_ylim(ybins.min(), ybins.max())
ax.set_xticks(xbins + 0.0001, minor=True)
ax.set_yticks(ybins + 0.0001, minor=True)
ax.grid(which='minor', color='dodgerblue', ls='--')
ax.set_aspect(1)
plt.show()
推荐阅读
- amazon-web-services - 用于创建触发 lambda 函数的云监视事件的 Terraform 代码
- java - 没有可用的名为“DAOBean”的 bean
- javascript - Jquery cookie插件从多个项目中删除项目
- networking - 如何知道我的测试(使用 JMeter)将产生的网络流量?
- java - 返回总和最大的数组。如果出现平局,则返回
- python - 我如何制作值元组?
- c - CMake:在工具链文件中添加编译器标志
- python - 使用 Dash 和 Plotly 的多页仪表板
- .net - 使用“DirectoryNotEmptyException”删除 .sonartmp 文件的 Sonarqube 扫描仪错误
- schema - 如何定义 Avro Schema 来捕获可能会出现或不会出现的键?