如果我向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()

当前回答

你可以在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。

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

另一种简单的解决方案是在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()

我一直在努力使用matplotlib修剪方法,所以我现在只是创建了一个函数,通过bash调用ImageMagick的mogrify命令来完成这一任务,该命令工作得很好,并从图形边缘获得所有额外的空白。这要求您使用UNIX/Linux,使用bash shell,并安装了ImageMagick。

只需在savefig()调用之后对其进行调用。

def autocrop_img(filename):
    '''Call ImageMagick mogrify from bash to autocrop image'''
    import subprocess
    import os

    cwd, img_name = os.path.split(filename)

    bashcmd = 'mogrify -trim %s' % img_name
    process = subprocess.Popen(bashcmd.split(), stdout=subprocess.PIPE, cwd=cwd)

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

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

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