如果我向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,但constrained_layout。参见此问题在matplotlib中用许多子图改进子图大小/间距

我发现立即添加子情节看起来更好。

fig, axs = plt.subplots(rows, cols, constrained_layout=True)

# then iterating over the axes to fill in the plots

但也可以在图形创建时添加:

fig = plt.figure(constrained_layout=True)

ax1 = fig.add_subplot(cols, rows, 1)
# etc

注意:为了使我的次要情节更接近,我还使用了

fig.subplots_adjust(wspace=0.05)

和constrained_layout不工作:(

其他回答

紧布局不工作与suptitle,但constrained_layout。参见此问题在matplotlib中用许多子图改进子图大小/间距

我发现立即添加子情节看起来更好。

fig, axs = plt.subplots(rows, cols, constrained_layout=True)

# then iterating over the axes to fill in the plots

但也可以在图形创建时添加:

fig = plt.figure(constrained_layout=True)

ax1 = fig.add_subplot(cols, rows, 1)
# etc

注意:为了使我的次要情节更接近,我还使用了

fig.subplots_adjust(wspace=0.05)

和constrained_layout不工作:(

从v3.3开始,tight_layout现在支持suptitle:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 3)
for i, ax in enumerate(axs):
    ax.plot([1, 2, 3])
    ax.set_title(f'Axes {i}')

fig.suptitle('suptitle')
fig.tight_layout()

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

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

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

你可以在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标签、轴标签和标题。因此,其他艺术家可能会被删减,也可能会重叠。

我有一个类似的问题,当使用tight_layout一个非常大的网格的情节(超过200个子情节),并在一个jupyter笔记本渲染。我做了一个快速的解决方案,总是把你的副标题放在你的顶部副标题上方的一定距离:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

对于可变大小的子图,您仍然可以使用此方法获得最上面的子图的顶部,然后手动定义一个额外的量添加到suptitle。