您可以在代码中轻松更改的一件事是您用于标题的fontsize。但是,我假设您不只是想这样做!
使用fig.subplots_adjust(top=0.85)的一些替代方法:
通常tight_layout() 可以很好地将所有内容放置在合适的位置,以免它们重叠。 tight_layout() 在这种情况下没有帮助的原因是因为 tight_layout() 没有考虑 fig.suptitle()。 GitHub 上有一个关于此的未解决问题:https://github.com/matplotlib/matplotlib/issues/829 [关闭2014 年,由于需要一个完整的几何管理器 - 转移到 https://github.com/matplotlib/matplotlib/issues/1109 ]。
如果您阅读了该主题,您的问题涉及GridSpec 的解决方案。关键是在调用tight_layout 时在图的顶部留出一些空间,使用rect kwarg。对于您的问题,代码变为:
使用 GridSpec
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure(1)
gs1 = gridspec.GridSpec(1, 2)
ax_list = [fig.add_subplot(ss) for ss in gs1]
ax_list[0].plot(f)
ax_list[0].set_title('Very Long Title 1', fontsize=20)
ax_list[1].plot(g)
ax_list[1].set_title('Very Long Title 2', fontsize=20)
fig.suptitle('Long Suptitle', fontsize=24)
gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
plt.show()
结果:
也许GridSpec 对您来说有点矫枉过正,或者您的真正问题将涉及更大画布上的更多子图,或其他复杂情况。一个简单的技巧是只使用annotate() 并将坐标锁定到'figure fraction' 以模仿suptitle。但是,一旦查看输出,您可能需要进行一些更精细的调整。请注意,第二个解决方案不使用tight_layout()。
更简单的解决方案(尽管可能需要微调)
fig = plt.figure(2)
ax1 = plt.subplot(121)
ax1.plot(f)
ax1.set_title('Very Long Title 1', fontsize=20)
ax2 = plt.subplot(122)
ax2.plot(g)
ax2.set_title('Very Long Title 2', fontsize=20)
# fig.suptitle('Long Suptitle', fontsize=24)
# Instead, do a hack by annotating the first axes with the desired
# string and set the positioning to 'figure fraction'.
fig.get_axes()[0].annotate('Long Suptitle', (0.5, 0.95),
xycoords='figure fraction', ha='center',
fontsize=24
)
plt.show()
结果:
[使用Python2.7.3(64位)和matplotlib1.2.0]