我在三个子图上共享一个居中的 xlabel 时遇到一些间歇性问题,这三个子图 1)仅跨越 gridspec 行的一部分,2)其相对于彼此的宽度可能会有所不同。
使用docs https://matplotlib.org/stable/tutorials/intermediate/gridspec.html我已经能够整理出我正在寻找的基本多图结构:
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 https://stackoverflow.com/a/22514587/9249533帮助我整理 y 轴共享。 setp 中的可见性 kwarg 提供了巨大的帮助。
This post https://stackoverflow.com/a/39003242/9249533帮助我(有点)获得了一个居中的通用 xlabel,但它有点像黑客,并且可能会根据 ax2、ax3、ax4 的相对宽度产生一些奇怪的行为(影响间距)。我必须迭代地猜测 x 偏移值。
我有更精确的方法来做到这一点吗?也许,标准化 xtick 标签格式(我知道如何一次性完成它们)。就像子网格规范中的子网格规范?或者,其他docs https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html显示“width_ratios”kwarg(尽管没有太多关于实现的信息)...这是否是一个更好的方法(即子图间距可能不那么敏感)?其他?
Cheers