六边形和直方图的不同行为

Mat*_*711 6 python matplotlib

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()
Run Code Online (Sandbox Code Playgroud)

您可以看到histogram2d旋转了-90度。我知道数据应该像hexbin图。

差异hexbin / histogram2d

ask*_*han 4

差异不在于计算直方图的方式,而在于绘制直方图的方式。您的数组H从数组左上角的 binnp.histogram开始,但将根据您的默认值进行绘制。您可以使用中的或关键字来控制它。4, -200originorigin=lowerorigin=upperplt.imshow

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)
Run Code Online (Sandbox Code Playgroud)

历史