Matplotlib(hist2D)中的2D直方图是如何工作的?

2024-04-19 04:06:03 发布

您现在位置:Python中文网/ 问答频道 /正文

hist2d function文档中:

plt.hist2d(x,y , weights=weight)

x和y以及权重都是数组,形状为(n,)。在

根据文件,产出之一是:

h : 2D array

The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.

如何创建二维阵列?想象一下

^{pr2}$

二维数组是如何从中创建出来的?在

我正在重画之前问的问题(它不是我的)。在


Tags: andthein文档functionplt数组are
1条回答
网友
1楼 · 发布于 2024-04-19 04:06:03

二维直方图与一维直方图的工作原理相同。你定义一些箱子,找出每个箱子里的数据点,然后计算每个箱子里的点数。如果直方图是加权的,则将权重相加,而不是仅仅计算数字。在

举个例子

x = [1.6, 2.3, 2.7]
y = [0.7, 1.8, 1.3]

我们要把它们放进有边的箱子里

^{pr2}$

另外,你的体重可能像

weights = [0.6, 1, 2]

把情况想象出来

sc = plt.scatter(x,y,c=weights, vmin=0)
plt.colorbar(sc)

plt.xticks(bins)
plt.yticks(bins)
plt.grid()
plt.show()

enter image description here

现在我们可以用肉眼观察柱状图:

在binx=1..2,y=0..1中有一个点。此点的权重为0.6,因此此bin的值将为0.6
在binx=2..3,y=1..2中有两个点。它们有重量1和{}。因此,该bin的值是1+2=3。在

其他的箱子都是空的。总的来说,你的直方图看起来像

[[ 0.0, 0.6, 0.0 ]
 [ 0.0, 0.0, 3.0 ]
 [ 0.0, 0.0, 0.0 ]]

这确实是我们让纽比做历史记录时得到的。在

values, _, _ = np.histogram2d(x,y, bins=bins, weights=weights)
print(values.T)

注意.T转置;这就是句子“x中的值沿着第一个维度被组织起来,y中的值沿着第二个维度被组织起来”想要告诉你的。在

plt.hist2dnumpy.histogram2d的包装器,它将把这个数组打印成图像

h,_, _, image = plt.hist2d(x,y,bins=bins, weights=weights)
plt.colorbar(image)
plt.show()

enter image description here

其中值以颜色编码。在

相关问题 更多 >