【发布时间】: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