This solution另一個線程建議使用gridspec.GridSpec
而不是plt.subplots
。然而,當我次要情節之間共享軸,我通常使用如下GridSpec在Python中共享座標軸
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
語法如何指定sharex
和sharey
當我使用GridSpec
?
This solution另一個線程建議使用gridspec.GridSpec
而不是plt.subplots
。然而,當我次要情節之間共享軸,我通常使用如下GridSpec在Python中共享座標軸
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
語法如何指定sharex
和sharey
當我使用GridSpec
?
首先,您的原始問題有一個更簡單的解決方法,只要您稍微不準確即可。只是重置次要情節爲默認的頂部範圍調用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()
但是,爲了回答你的問題,你需要在稍微創造次要情節較低級別使用gridspec。如果您想複製像subplots
這樣的共享軸的隱藏功能,則需要手動執行該操作,方法是使用sharey
參數Figure.add_subplot
,並用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()
兩個Joe的選擇,給了我一些問題:前者,可直接使用的figure.tight_layout
代替figure.set_tight_layout()
和,後者有關,與一些後端(UserWarning:tight_layout:回退到Agg渲染器)。但是喬的回答完全清除了我的另一種緊湊型選擇。這是結果的問題接近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()