如果我向matplotlib图添加一个副标题,它会被副图的标题覆盖。有人知道怎么简单地处理吗?我尝试了tight_layout()函数,但它只会让事情变得更糟。

例子:

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.tight_layout()
plt.show()

当前回答

正如其他人提到的,默认情况下紧凑的布局不考虑suptitle。然而,我发现可以使用bbox_extra_artists参数来传递suptitle作为一个应该考虑的边界框:

st = fig.suptitle("My Super Title")
plt.savefig("figure.png", bbox_extra_artists=[st], bbox_inches='tight')

这迫使紧凑的布局计算考虑到副标题,它看起来像你所期望的。

其他回答

正如其他人提到的,默认情况下紧凑的布局不考虑suptitle。然而,我发现可以使用bbox_extra_artists参数来传递suptitle作为一个应该考虑的边界框:

st = fig.suptitle("My Super Title")
plt.savefig("figure.png", bbox_extra_artists=[st], bbox_inches='tight')

这迫使紧凑的布局计算考虑到副标题,它看起来像你所期望的。

唯一对我有用的是修改对suptitle的调用:

fig.suptitle("title", y=.995)

你可以在very tight_layout调用中调整subplot几何形状,如下所示:

fig.tight_layout(rect=[0, 0.03, 1, 0.95])

正如文档中所述(https://matplotlib.org/users/tight_layout_guide.html):

Tight_layout()只考虑tick标签、轴标签和标题。因此,其他艺术家可能会被删减,也可能会重叠。

这个网站有一个简单的解决方案,其中有一个对我有用的例子。为标题实际留出空间的代码行如下:

plt.tight_layout(rect=[0, 0, 1, 0.95]) 

下面是一张证明它对我有效的图片:

另一种简单的解决方案是在suptitle的调用中使用y参数来调整图中suptitle文本的坐标(见文档):

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()