【问题标题】:Arrange matplotlib subplots in skewed grid在倾斜网格中排列 matplotlib 子图
【发布时间】:2018-01-11 15:07:17
【问题描述】:

使用 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) 排列作为示例,我也希望对任意集合执行此操作,而不仅仅是这个。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

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

    这里有 3 行 6 列,每个子图跨越 1 行和 2 列,只是第一行中的子图跨越子图位置 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()
    

    【讨论】:

    • 嗯.. 是的,我确实考虑过这一点。让我看看概括它是多么容易。
    • 实际上,如果它们总是长度为 n 或长度为 n-1,那么做一个n * 2 网格就足够了,所以这很简单。
    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2019-02-05
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多