You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib子图时如何为多行suptitle预留足够垂直空间?

解决Matplotlib子图多行标题的垂直空间问题

嘿,我来帮你搞定这个多行标题被挤到的问题~首先提个小细节:你原来的代码里,fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 3))已经创建了两个子图对象,但后面又用ax1 = fig.add_subplot(121)重新创建,这其实会覆盖之前的子图,完全没必要,我们可以直接用一开始生成的ax1和ax2哦。

回到核心问题:fig.tight_layout()默认只会优化子图、轴标签这些元素的空间,不会考虑顶部的suptitle,所以多行标题很容易被截断。这里有几个实用的解决办法:

方法1:用tight_layout的rect参数留出顶部空间

tight_layout的rect参数可以指定子图区域的位置(格式是[left, bottom, width, height],取值范围0-1),我们可以把顶部的空间留出来给多行标题:

import matplotlib.pylab as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 3))
# 设置多行标题
fig.suptitle("Figure 1: Some test title \n With a Second line \n And a Third line", fontsize=12)

# 直接用一开始创建的子图
ax1.set_title("Model 1")
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
ax1.plot(x, y)

ax2.set_title("Model 2")
x = np.linspace(0, 2 * np.pi, 400)
y = np.cos(x ** 2)
ax2.plot(x, y)

# rect参数:[左, 下, 宽, 高],这里把顶部留出0.2的空间给标题
fig.tight_layout(rect=[0.1, 0.1, 0.8, 0.8])
plt.show()

方法2:用subplots_adjust直接调整顶部边距

如果觉得tight_layout的rect参数不好把控,也可以直接用subplots_adjust调整顶部的边距,给标题腾地方:

import matplotlib.pylab as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 3))
fig.suptitle("Figure 1: Some test title \n With a Second line \n And a Third line", fontsize=12)

ax1.set_title("Model 1")
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
ax1.plot(x, y)

ax2.set_title("Model 2")
x = np.linspace(0, 2 * np.pi, 400)
y = np.cos(x ** 2)
ax2.plot(x, y)

# 调整顶部边距,top值越小,顶部留的空间越大
plt.subplots_adjust(top=0.75)
fig.tight_layout()
plt.show()

方法3:调整suptitle的垂直位置

还可以直接把suptitle往上挪,配合tight_layout使用,不过这个方法要根据标题行数微调y值:

import matplotlib.pylab as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 3))
# y参数设置标题的垂直位置,1是顶部,这里设为0.95让标题往上移
fig.suptitle("Figure 1: Some test title \n With a Second line \n And a Third line", fontsize=12, y=0.95)

ax1.set_title("Model 1")
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
ax1.plot(x, y)

ax2.set_title("Model 2")
x = np.linspace(0, 2 * np.pi, 400)
y = np.cos(x ** 2)
ax2.plot(x, y)

fig.tight_layout()
plt.show()

这几个方法里,我个人更推荐方法1和方法2,它们能更稳定地给多行标题留出足够的垂直空间,不会因为标题行数变化而频繁调整参数~

内容的提问来源于stack exchange,提问作者tcs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:22:48