python - 如何从 bin 生成直方图?
问题描述
我有一些数据作为 numpy 数组x, y, v
,如下面的代码所示。
这实际上velocity (v)
是 xy 平面中尘埃粒子的虚拟数据。
我已经将我的数据分成 4 个 bin,对于每个 bin,我计算了每个 bin 中条目的平均值并制作了一张热图。
现在我想要做的是v
在每个 bin中制作一个直方图/分布,并0
以直方图的中心为中心。
我不想再绘制平均值,只想将我的数据划分到与此代码相同的箱中,并且对于每个箱,我想生成箱中值的直方图。
我该怎么做?
我认为这是一种模拟气体粒子发射线光谱的方法。任何帮助表示赞赏!谢谢!
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
x = np.array([-10,-2,4,12,3,6,8,14,3])
y = np.array([5,5,-6,8,-20,10,2,2,8])
v = np.array([4,-6,-10,40,22,-14,20,8,-10])
x_bins = np.linspace(-20, 20, 3)
y_bins = np.linspace(-20, 20, 3)
H, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins], weights = v)
pstat = stats.binned_statistic_2d(x, y, v, statistic='mean', bins = [x_bins, y_bins])
plt.xlabel("x")
plt.ylabel("y")
plt.imshow(pstat.statistic.T, origin='lower', cmap='RdBu',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
plt.colorbar().set_label('mean', rotation=270)
编辑:请注意,我的原始数据很大。我的 x、y、v 数组非常大,我使用的是 30x30 网格,也就是说,不仅仅是 4 个象限,而是 900 个箱。我可能还需要增加垃圾箱号。因此,我们希望找到一种方法来自动将“v”数据分成规则间隔的 bin,然后能够绘制每个 bin 中“v”数据的直方图。
解决方案
我将遍历压缩的 x 和 y,然后标记 v 是否在象限内并将它们附加到象限列表中。之后,您可以绘制任何您想要的内容:
x = np.array([-10,-2,4,12,3,6,8,14,3])
y = np.array([5,5,-6,8,-20,10,2,2,8])
v = np.array([4,-6,-10,40,22,-14,20,8,-10])
q1 = []
q2 = []
q3 = []
q4 = []
for i, (x1,y1) in enumerate(zip(x,y)):
if x1<0 and y1>=0:
q1.append(v[i])
elif x1>=0 and y1>=0:
q2.append(v[i])
elif x1>=0 and y1<0:
q3.append(v[i])
elif x1<0 and y1<0:
q4.append(v[i])
print(q1)
print(q2)
print(q3)
print(q4)
#[4, -6]
#[40, -14, 20, 8, -10]
#[-10, 22]
#[]
plt.hist(q1, density=True)
plt.hist(q2, density=True)
plt.hist(q3, density=True)
#q4 is empty
推荐阅读
- python - FileNotFoundError: `[Errno 2] No such file or directory: ' 用于根据几个类显示条形图
- php - 使用 array_search() 检查值是否存在
- python - Pi UART接收额外字节
- google-colaboratory - 在 colab 上使用 CONDA 安装软件包时出错
- javascript - 从 json 树中获取所需键的值
- reactjs - 为什么在使用功能过去时不需要对反应进行反应?
- c++ - 返回捕获 lambda 的 lambda 时发出 Clang 警告
- statsmodels - statsmodels.logit 如何处理连续但有界 (0,1) 的目标值?
- android - 如何在本机反应中使状态栏透明?
- database - 如何在 Tableau 中用另一个数字替换一个数字?