hexbin和histogram2d的行为差异
hexbin和histogram2d有什么区别呢?
f, (ax1,ax2) = plt.subplots(2)
ax1.hexbin(vradsel[0], distsel[0],gridsize=20,extent=-200,200,4,20],cmap=plt.cm.binary)
H, xedges, yedges =np.histogram2d(vradsel[0], distsel[0],bins=20,range=[[-200,200],[4,20]])
ax2.imshow(H, interpolation='nearest', cmap=plt.cm.binary, aspect='auto',extent=[xedges[0],xedges[-1],yedges[0],yedges[-1]])
plt.show()
你可以看到,histogram2d的图像是旋转了-90度。我知道数据应该和hexbin图的样子一样。
1 个回答
4
这里的区别不是在于直方图的计算方式,而是在于你绘制直方图的方式。你从 np.histogram
得到的数组 H
的左上角是 4, -200
这个区间,但它的绘制方式取决于你默认的 origin
值。你可以通过在 plt.imshow
中使用 origin=lower
或 origin=upper
来控制这一点。
不过,origin
只是镜像图像,所以你还需要记住,在图像中,水平轴 x
是第一个,垂直轴 y
是第二个,这和数组是相反的。因此,在绘图之前,你还需要对 H
进行转置。
我建议直接使用 plt.hist2d()
,这样它会自动调整范围和方向,就像 plt.hexbin
一样。你仍然可以像使用 numpy 版本那样访问结果:H, x, y, im = ax.hist2d(...)
,但它会自动生成图表。
a = np.random.rand(100)*400 - 200
b = np.random.rand(100)*16 + 4
a[:10] = -200
b[:10] = 4
f, ax = plt.subplots(3)
ax[0].hexbin(a, b, gridsize=20, extent=[-200,200,4,20], cmap=plt.cm.binary)
H, xedges, yedges = np.histogram2d(a, b, bins=20, range=[[-200,200],[4,20]])
ax[1].imshow(H.T, interpolation='nearest', cmap=plt.cm.binary, aspect='auto',
extent=[xedges[0],xedges[-1],yedges[0],yedges[-1]], origin='lower')
# simplest and most reliable:
ax[2].hist2d(a, b, bins=20, range=[[-200,200],[4,20]], cmap=plt.cm.binary)