破碎的子图不占据整个图

Crushed subplots not occupying the whole plot

不知道为什么,我的次要情节完全被压碎了,而不是占据整个情节。

此外,我希望子图具有相同的长度,颜色条也一样。这里看起来前 2 个子图比第 3 个短,因为颜色条更大。

理想情况下我想要这样的结果: 但是 pcolormesh 的质量(imshow 的质量真的很差)和 2 个颜色条。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig  = plt.figure()

grid_top = ImageGrid(fig, 211, nrows_ncols = (2, 1),
                     cbar_location = "right",                     
                     cbar_mode="single",
                     cbar_pad=.2) 
grid_bot = ImageGrid(fig, 212, nrows_ncols = (1, 1),
                     cbar_location = "right",                     
                     cbar_mode="single",
                     cbar_pad=.2) 

im1 = grid_top[0].pcolormesh(np.arange(0,len(array1[0])),np.arange(0,len(array1)+1),array1, vmin=0, vmax=0.8)
im2 = grid_top[1].pcolormesh(np.arange(0,len(array2[0])),np.arange(0,len(array2)+1),array2, vmin=0, vmax=0.8)
im3 = grid_bot[0].pcolormesh(np.arange(0,len(array3[0])),np.arange(0,len(array3)+1),array3, vmin=-0.5, vmax=0.5, cmap='seismic')

grid_top.cbar_axes[0].colorbar(im1)
grid_bot.cbar_axes[0].colorbar(im3)

plt.show()

这是结果,为什么它如此破碎,为什么支线没有占据整个情节?

您似乎需要为 ImageGrid 个实例 (see the docs for ImageGrid here) 设置 aspect=False [h/t @daryl]

aspect

By default (False), widths and heights of axes in the grid are scaled independently. If True, they are scaled according to their data limits (similar to aspect parameter in mpl).

获取您的代码,并将 aspect=False 添加到 grid_topgrid_bot,产生以下结果:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig  = plt.figure()

grid_top = ImageGrid(fig, 211, nrows_ncols = (2, 1),
                     cbar_location = "right",                     
                     cbar_mode="single",
                     cbar_pad=.2,
                     aspect=False) 
grid_bot = ImageGrid(fig, 212, nrows_ncols = (1, 1),
                     cbar_location = "right",                     
                     cbar_mode="single",
                     cbar_pad=.2,
                     aspect=False) 

# Some random data so the script will run
array1=np.random.rand(10,250)
array2=np.random.rand(10,250)
array3=np.random.rand(10,250)

im1 = grid_top[0].pcolormesh(np.arange(0,len(array1[0])),np.arange(0,len(array1)+1),array1, vmin=0, vmax=0.8)
im2 = grid_top[1].pcolormesh(np.arange(0,len(array2[0])),np.arange(0,len(array2)+1),array2, vmin=0, vmax=0.8)
im3 = grid_bot[0].pcolormesh(np.arange(0,len(array3[0])),np.arange(0,len(array3)+1),array3, vmin=-0.5, vmax=0.5, cmap='seismic')

grid_top.cbar_axes[0].colorbar(im1)
grid_bot.cbar_axes[0].colorbar(im3)

plt.show()