跨 gridspec subplots/axes 共享 xlabel(部分行)

sharing of xlabel across gridspec subplots/axes (partial row)

我在三个子图中共享一个居中的 xlabel 时遇到一些间歇性问题,这些子图 1) 仅跨越 gridspec 行的一部分,并且 2) 其相对宽度可能会有所不同。

使用 docs 我已经能够整理出我正在寻找的基本多图结构:

fig = plt.figure(figsize=(10,8), constrained_layout=True)
xlabel_234 = 'XLabel Thing2\n(to be centered under ax2, ax3, and ax4 with equal horiz. spacing btwn subplots)'
gs = fig.add_gridspec(nrows=14, ncols=1)

gs0 = gs[0:2]
gs1 = gs[2:].subgridspec(nrows=1, ncols=12)

ax1 = fig.add_subplot(gs0)
ax1.set_title('Something Short and Wide')
ax1.text(0.5, 0.5, 'ax1', ha='center')
ax1.set_xlabel('XLabel Thing1')

ax2 = fig.add_subplot(gs1[0, 0:1])
ax2.set_title('Something Tall\nand Narrow 2a')
ax2.text(0.5, 0.5, 'ax2', ha='center')

ax3 = fig.add_subplot(gs1[0, 1:6], sharey=ax2)
ax3.set_title('Something Tall\nand Narrow 2b')
ax3.text(0.5, 0.5, 'ax3', ha='center')
plt.setp(ax3.get_yticklabels(), visible=False)
ax3.set_xlabel(xlabel_234, x=0.7)   # *x offset is a bit of hack*

ax4 = fig.add_subplot(gs1[0, 6:9], sharey=ax2)
ax4.set_title('Something Tall\n and Narrow 2c')
ax4.text(0.5, 0.5, 'ax4', ha='center')
plt.setp(ax4.get_yticklabels(), visible=False)

ax5 = fig.add_subplot(gs1[0, 9:12])
ax5.set_title('Something Tall\nand Narrow 3')
ax5.text(0.5, 0.5, 'ax5', ha='center')
ax5.set_xlabel('XLabel Thing3')

感谢这个 post 帮助我整理了 y 轴共享。 setp 中的 visibility kwarg 是一个巨大的帮助。

这个 post 帮助我(有点)让一个通用的 xlabel 居中,但它有点 hack,并且会产生一些奇怪的行为(影响间距),具体取决于 ax2、ax3、斧头4。而且我必须反复猜测 x 偏移值。

有没有更精确的方法让我做到这一点?而且,也许,标准化 xtick 标签格式(我知道如何一次性完成)。就像子网格规范的子网格规范一样?或者,其他 docs 显示 'width_ratios' kwarg(虽然没有太多关于实施的信息)......这会是更好的方法吗(即子图间距可能不那么敏感)?其他?

干杯

最近的一些功能 (matplotlib 3.4.0+) 可以提供帮助:

  • subfigures:有自己的布局并且可以嵌套在其他(子)图形中的虚拟图形
  • supxlabel/supylabel: common axis labels(子)数字

您可以使用它们以多种方式重现您的布局,但这里有一个示例供参考:

  1. 创建 top/bottom 个子图(ax0 的顶部子图)
  2. 在底部子图中嵌套 left/right 个子图(ax1-[=16= 的左子图,ax4 的右子图)
  3. 在左下角的子图中,使用自定义 gridspecsupxlabel(对于 ax1-ax3
fig = plt.figure(constrained_layout=True, figsize=(10, 8))

# create top/bottom subfigs
(subfig_t, subfig_b) = fig.subfigures(2, 1, hspace=0.05, height_ratios=[1, 3])

# put ax0 in top subfig
ax0 = subfig_t.subplots()
ax0.set_title('ax0')
subfig_t.supxlabel('xlabel0')

# create left/right subfigs nested in bottom subfig
(subfig_bl, subfig_br) = subfig_b.subfigures(1, 2, wspace=0.1, width_ratios=[3, 1])

# put ax1-ax3 in gridspec of bottom-left subfig
gs = subfig_bl.add_gridspec(nrows=1, ncols=9)
ax1 = subfig_bl.add_subplot(gs[0, :1])
ax2 = subfig_bl.add_subplot(gs[0, 1:6], sharey=ax1)
ax3 = subfig_bl.add_subplot(gs[0, 6:], sharey=ax1)
ax1.set_title('ax1')
ax2.set_title('ax2')
ax3.set_title('ax3')
ax2.get_yaxis().set_visible(False)
ax3.get_yaxis().set_visible(False)
subfig_bl.supxlabel('xlabel1-3')

# put ax4 in bottom-right subfig
ax4 = subfig_br.subplots()
ax4.set_title('ax4')
subfig_br.supxlabel('xlabel4')