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

如何将Matplotlib图表标题从第二个逗号处拆分为两行?

解决Matplotlib标题从第二个逗号处换行的问题

现有字典d,已将其键值对拼接成字符串res作为Matplotlib图表标题,但res过长,需要从第二个逗号位置拆分为两行标题。当前实现代码及效果如下:

原处理代码

d = {'lag(0)_pred': 0.83,
'lag(1)_pred': 0.51,
'lag(2)_pred': 0.17,
'lag(3)_pred': 0.52
}

out = [f'{key}: {d[key]:.2f}' for key in d]
res = ", ".join(out)

输出的res为:

'lag(0)_pred: 0.83, lag(1)_pred: 0.51, lag(2)_pred: 0.17, lag(3)_pred: 0.52'

原绘图代码

import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
plt.title(f"{res}", loc='center', wrap=True)
plt.show()

效果对比

  • 当前效果:当前效果:标题自动换行位置不符合预期
  • 预期效果:预期效果:标题在第二个逗号处拆分为两行

解决方案

核心思路是精准定位第二个逗号的位置,手动插入换行符\n,替代无法控制换行位置的wrap=True参数。

修改后的完整代码

d = {'lag(0)_pred': 0.83,
'lag(1)_pred': 0.51,
'lag(2)_pred': 0.17,
'lag(3)_pred': 0.52
}

out = [f'{key}: {d[key]:.2f}' for key in d]
res = ", ".join(out)

# 定位第二个逗号的位置
first_comma_idx = res.find(',')
second_comma_idx = res.find(',', first_comma_idx + 1)
# 在第二个逗号后插入换行,替换原有的逗号+空格
split_title = res[:second_comma_idx] + '\n' + res[second_comma_idx + 2:]

# 绘图部分
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]
plt.figure(figsize=(8, 5))
plt.plot(x, y)
# 使用手动拆分后的标题,无需wrap=True
plt.title(split_title, loc='center')
plt.show()

代码说明

  1. 通过str.find()方法先找到第一个逗号的索引,再从该索引后查找第二个逗号的位置,实现精准定位;
  2. 拆分字符串并插入\n,将第二个逗号后的内容移至新行;
  3. 绘图时直接使用拆分后的标题字符串,确保换行位置完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:05:20