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

如何调整Matplotlib布局,使标题相对图表与图例整体居中

解决Matplotlib标题相对图表+图例整体居中的问题

要让标题相对于图表和图例的整体区域居中,核心是让Matplotlib在布局时把图例空间纳入整体计算,以下是两种简洁可行的方案:

方案一:用全局标题配合自动布局

这种方法直接让标题适配整个画布(包含图例)的宽度,操作最简单:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,1000)
y1 = np.sin(x)
y2 = np.cos(x)

# 使用子图对象管理布局
fig, ax = plt.subplots()
ax.plot(x,y1)
ax.plot(x,y2)

# 设置全局标题,默认居中整个画布
fig.suptitle("A very long title that makes the graph shorter than the title itself, it's so long it makes me sick to the core", y=1.02)
# 放置图例到图外
ax.legend(["sin x", "cos x"], bbox_to_anchor = [1,0.5], loc = "center left", fontsize = 20)

# 自动调整布局,适配图例空间
fig.tight_layout()
plt.show()

方案二:手动调整标题位置(精细控制)

如果坚持使用plt.title,可以通过计算画布总宽度,手动设置标题的水平对齐点:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x,y1)
plt.plot(x,y2)

# 先绘制图例,获取其尺寸信息
legend = plt.legend(["sin x", "cos x"], bbox_to_anchor = [1,0.5], loc = "center left", fontsize = 20)
ax = plt.gca()
fig = plt.gcf()

# 计算坐标轴+图例的总宽度
ax_width = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()).width
legend_width = legend.get_window_extent().transformed(fig.dpi_scale_trans.inverted()).width
total_width = ax_width + legend_width

# 设置标题水平居中于总宽度,y参数调整标题与图表的间距
plt.title("A very long title that makes the graph shorter than the title itself, it's so long it makes me sick to the core", 
          x=total_width/2, y=1.02)
# 为图例预留右侧空间
plt.subplots_adjust(right=0.8)
plt.show()

关键提示

  • 方案一更适合常规场景,tight_layout()会自动处理元素间距,避免重叠;y=1.02是为了防止标题被图表或图例截断。
  • 方案二更适合需要精细调整布局的场景,可根据实际需求修改subplots_adjust的参数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:59:55