在倾斜网格中排列 matplotlib 子图

Arrange matplotlib subplots in skewed grid

使用 matplotlib,我想在每行具有不同列数的网格上显示多个子图,其中每个子图的大小大致相同,并且子图的排列方式使它们或多或少居中,像这样:

gridspec 创建一个具有 2、3、2 模式的网格是一件相当简单的事情,但问题是 gridspec,不出所料,将它们对齐到一个网格,因此,包含 2 个地块的行中的地块更宽:

这是生成它的代码:

from matplotlib import gridspec
from matplotlib import pyplot as plt

fig = plt.figure()

arrangement = (2, 3, 2)
nrows = len(arrangement)

gs = gridspec.GridSpec(nrows, 1)
ax_specs = []
for r, ncols in enumerate(arrangement):
    gs_row = gridspec.GridSpecFromSubplotSpec(1, ncols, subplot_spec=gs[r])
    for col in range(ncols):
        ax = plt.Subplot(fig, gs_row[col])
        fig.add_subplot(ax)

for i, ax in enumerate(fig.axes):
    ax.text(0.5, 0.5, "Axis: {}".format(i), fontweight='bold',
            va="center", ha="center")
    ax.tick_params(axis='both', bottom='off', top='off', left='off',
                   right='off', labelbottom='off', labelleft='off')

plt.tight_layout()

我知道我可以设置一堆子图并通过计算它的几何形状来调整它们的排列,但我认为它可能会变得有点复杂,所以我希望可能有更简单的方法可用.

我应该注意,即使我使用 (2, 3, 2) 排列作为示例,我也想对任意集合执行此操作,而不仅仅是这个。

这个想法通常是找到子图之间的共同点,即可以组成所需网格的最大子图,并将所有子图跨越其中的几个子图,从而实现所需的布局。

这里有 3 行 6 列,每个子图跨越 1 行和两列,只是第一行中的子图跨越子图位置 1/2 和 3/4,而在第二行中它们跨越位置0/1、2/3、4/5。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(3, 6)
ax1a = plt.subplot(gs[0, 1:3])
ax1b = plt.subplot(gs[0, 3:5])
ax2a = plt.subplot(gs[1, :2])
ax2b = plt.subplot(gs[1, 2:4])
ax2c = plt.subplot(gs[1, 4:])
ax3a = plt.subplot(gs[2, 1:3])
ax3b = plt.subplot(gs[2, 3:5])


for i, ax in enumerate(plt.gcf().axes):
    ax.text(0.5, 0.5, "Axis: {}".format(i), fontweight='bold',
            va="center", ha="center")
    ax.tick_params(axis='both', bottom='off', top='off', left='off',
                   right='off', labelbottom='off', labelleft='off')

plt.tight_layout()

plt.show()