Python中带有共享轴的GridSpec

2024-04-25 23:10:01 发布

您现在位置:Python中文网/ 问答频道 /正文

另一个线程的This solution建议使用gridspec.GridSpec,而不是plt.subplots。但是,当我在子块之间共享轴时,我通常使用如下语法

  fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))

使用GridSpec时,如何指定sharexsharey


Tags: 语法figpltcolthis线程建议子块
2条回答

首先,有一个更容易解决你原来的问题的办法,只要你能接受稍微不精确。只需在调用tight_layout之后将子块的顶部范围重置为默认值:

fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)

fig.tight_layout()
fig.subplots_adjust(top=0.9) 

plt.show()

enter image description here


但是,要回答您的问题,您需要在稍低的级别创建子块才能使用gridspec。如果要复制共享轴的隐藏,如subplots所做的,则需要使用sharey参数对^{}进行手动操作,并使用plt.setp(ax.get_yticklabels(), visible=False)隐藏重复的记号。

例如:

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()
gs = gridspec.GridSpec(1,2)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)

plt.setp([ax1, ax2], title='Test')
fig.suptitle('An overall title', size=20)
gs.tight_layout(fig, rect=[0, 0, 1, 0.97])

plt.show()

enter image description here

乔的两个选择都给了我一些问题:前者与直接使用figure.tight_layout而不是figure.set_tight_layout()有关,后者与一些后端(UserWarning:tight_layout:falling back to Agg renderer)有关。但乔的回答无疑为我找到了另一个紧凑的选择。这是接近OP的问题的结果:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=1, sharex='col', sharey=True,
                               gridspec_kw={'height_ratios': [2, 1]},
                               figsize=(4, 7))
fig.set_tight_layout({'rect': [0, 0, 1, 0.95], 'pad': 1.5, 'h_pad': 1.5})
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)

plt.show()

enter image description here

相关问题 更多 >