更改子图大小并使用 histogram2d 添加颜色条

Changing subplot sizes and adding colorbar with histogram2d

我正在尝试创建一个具有 1 行和 3 列的图形,但遇到了很多问题。首先,我的子图变成了非常小的小条子,并且在尝试添加颜色条时出现错误。我怎样才能让子图成为盒子,颜色条显示在最右边?

rmax0、rmax1 和 rmax2 的范围都在 0 到 700 之间(大多数小于 200),fspd 的范围在 0 到 10 之间。

import matplotlib.pyplot as plt
import numpy as np

ax1 = plt.subplot(131)
nice = plt.get_cmap('BuPu')
bins1 = np.arange(0,700,700/50.0)
bins2 = np.arange(0,10,10/50.0)
h,xedges,yedges = np.histogram2d(rmax0,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
ax1.pcolormesh(X, Y, h,cmap=nice)
ax1.set_aspect('equal')
plt.xlim([0,200])
plt.ylim([0,10])

ax2 = plt.subplot(132)
h,xedges,yedges = np.histogram2d(rmax1,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
ax2.pcolormesh(X, Y, h,cmap=nice)
ax2.set_aspect('equal')
plt.xlim([0,200])
plt.ylim([0,10])

ax3 = plt.subplot(133)
h,xedges,yedges = np.histogram2d(rmax2,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
ax3.pcolormesh(X, Y, h,cmap=nice)
ax3.set_aspect('equal')
plt.xlim([0,200])
plt.ylim([0,10])
plt.colorbar()

plt.show()

当我添加 plt.colorbar() 行时,出现以下错误: RuntimeError:未发现可映射可用于创建颜色条。首先定义一个可映射对象,例如图像(使用 imshow)或轮廓集(使用 contourf)。

你的图最终变成了细小的碎片,因为你强制了纵横比。尝试禁用这些行:

ax1.set_aspect('equal')
ax2.set_aspect('equal')
ax3.set_aspect('equal')

如果你这样调用它,颜色条将显示:

p = ax3.pcolormesh(X, Y, h, cmap=nice)
plt.colorbar(p, ax=[ax1, ax2, ax3])

我在这里将所有轴的列表传递给 colorbar,以使颜色条缩小所有三个子图以腾出空间。如果你省略这个,space 将只取自最后一个子图,使这个子图的宽度小于其他的。

复制粘贴我用来测试这个的完整代码:

import matplotlib.pyplot as plt
import numpy as np

rmax0 = np.random.rand(1000) * 700
rmax1 = np.random.rand(1000) * 700
rmax2 = np.random.rand(1000) * 700
fspd = np.random.rand(1000) * 10

ax1 = plt.subplot(131)
nice = plt.get_cmap('BuPu')
bins1 = np.arange(0,700,700/50.0)
bins2 = np.arange(0,10,10/50.0)
h,xedges,yedges = np.histogram2d(rmax0,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
ax1.pcolormesh(X, Y, h,cmap=nice)
ax1.set_aspect('auto')
plt.xlim([0,200])
plt.ylim([0,10])

ax2 = plt.subplot(132)
h,xedges,yedges = np.histogram2d(rmax1,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
ax2.pcolormesh(X, Y, h,cmap=nice)
ax2.set_aspect('auto')
plt.xlim([0,200])
plt.ylim([0,10])

ax3 = plt.subplot(133)
h,xedges,yedges = np.histogram2d(rmax2,fspd,bins=[bins1,bins2],normed=True)
X,Y = np.meshgrid(xedges,yedges)
p = ax3.pcolormesh(X, Y, h,cmap=nice)
ax3.set_aspect('auto')
plt.xlim([0,200])
plt.ylim([0,10])
plt.colorbar(p, ax=[ax1, ax2, ax3])

plt.show()