在matplotlib中创建多个大小不等的列和行

在matplotlib中创建多个大小不等的列和行,matplotlib,multiple-columns,Matplotlib,Multiple Columns,我需要在matplotlib中创建多个大小不等的列和行。下面是一个示例代码: a = np.random.rand(20, 20) b = np.random.rand(20, 5) c = np.random.rand(5, 20) d = np.random.rand(5,5) arrays = [a,b,c,d] fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10)) for ax, ar in

我需要在matplotlib中创建多个大小不等的列和行。下面是一个示例代码:

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10))
for ax, ar in zip(axs.flatten(), arrays):
    ax.imshow(ar)
然而,我得到了这个结果

右栏的第一行和第二行的图像宽度不等,我希望它们相等(基本上缩小右下角的图像,使其与其他图像具有相同的比例)。
我对此进行了大量研究,但似乎没有任何效果。我试过tight_layout(),其他一些格式化技巧,但都没有用…

您可以使用gridspec的
高度比
宽度比
参数来设置子地块应占据的所需比例

在这种情况下,由于对称性,这只是形状,例如
b

import numpy as np
import matplotlib.pyplot as plt

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10), 
                        gridspec_kw={"height_ratios" : b.shape, 
                                     "width_ratios" : b.shape})
for ax, ar in zip(axs.flatten(), arrays):
    ax.imshow(ar)

plt.show()

或者,更一般地说

gridspec_kw={"height_ratios" : [a.shape[0], c.shape[0]], 
              "width_ratios" : [a.shape[1], b.shape[1]]}

谢谢,这正是我想要的!