2014-03-19 111 views

回答

40

首先,您的原始問題有一個更簡單的解決方法,只要您稍微不準確即可。只是重置次要情節爲默認的頂部範圍調用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參數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() 

enter image description here

7

兩個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() 

enter image description here