求助:如何在Matplotlib折线图中为y2系列添加数值标注
解决Matplotlib折线图中y2系列无法添加数值标注的问题
问题原因
你的代码仅对y1系列执行了标注循环,未处理y2;另外循环里用for x, y in zip(x, y1)会覆盖原始的x列表变量,哪怕之后想补加y2的循环,也会因为x已变成单个元素而报错。
修正方案
- 重命名循环变量,避免覆盖原始数据列表
- 为y2系列添加对应的标注循环,可调整标注偏移位置避免和y1标注重叠
完整修正代码
import matplotlib.pyplot as plt plt.figure(figsize=(10,4)) x = [201901, 202001, 202101, 202202] y1 = [6.86, 21.45, 6.25, 0.88] y2 = [6.33, 6.33, 7.04, 5.63] plt.box(False) plt.plot(x, y1, marker='o', label='Your Return') plt.plot(x, y2, marker='o', label='Benchmark') # 修正拼写错误:Benckmark → Benchmark plt.legend() plt.title('Your Return vs Benchmark', pad=30) plt.xlabel('Period') plt.ylabel('Return') # 为y1添加标注,循环变量用xi避免覆盖原始x for xi, y in zip(x, y1): plt.annotate(f'{y:.2f}', (xi, y), xycoords="data", textcoords="offset points", xytext=(0, 10), ha="center") # 为y2添加标注,调整偏移到下方避免重叠 for xi, y in zip(x, y2): plt.annotate(f'{y:.2f}', (xi, y), xycoords="data", textcoords="offset points", xytext=(0, -15), ha="center") plt.show()
额外优化说明
- 把标注格式化为
{y:.2f}确保数值显示一致的小数位数 - 修正了原代码中
Benckmark的拼写错误为Benchmark - 调整y2标注的
xytext为(0, -15),让标注显示在点的下方,和y1的上方标注不重叠,可读性更好
内容的提问来源于stack exchange,提问作者Deivid
相关产品推荐
相关产品推荐

