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

如何在Matplotlib的for循环中为每条折线添加唯一标签?

解决方法:为循环绘制的折线添加唯一标签

没问题呀!你的思路完全正确,只是代码里有个小细节没处理对,导致图例可能没有正常显示出来。我来帮你修正并优化一下:

问题出在哪?

你写的plt.legend('upper left')是错误的——legend()函数的第一个参数是用来手动指定图例标签的列表,而不是位置参数。要设置图例位置,应该用loc参数来传递位置字符串。

修正后的代码

import matplotlib.pyplot as plt

my_list = [1, 2, 3, 4]
other_list = [[1, 1.2, 1.4, 1.6], [0.8, 0.9, 0.7, 0.6], [1.9, 1.3, 1.4, 1.0], [0.1, 0.2, 0.4, 0.6]]

for i in range(len(my_list)):
    # 这里用f-string比%s格式化更简洁直观,效果是一样的
    plt.plot(my_list, other_list[i], label=f'Line {i}')

# 正确指定图例位置为左上角
plt.legend(loc='upper left')
# 别忘了显示图像
plt.show()

更优雅的写法:用enumerate循环

既然你是遍历other_list里的每条折线数据,用enumerate可以直接拿到索引和对应的数据,不用手动计算长度,代码更简洁:

import matplotlib.pyplot as plt

my_list = [1, 2, 3, 4]
other_list = [[1, 1.2, 1.4, 1.6], [0.8, 0.9, 0.7, 0.6], [1.9, 1.3, 1.4, 1.0], [0.1, 0.2, 0.4, 0.6]]

for idx, line_data in enumerate(other_list):
    plt.plot(my_list, line_data, label=f'Line {idx}')

plt.legend(loc='upper left')
plt.show()

额外小调整

如果你希望标签从1开始计数(比如Line 1、Line 2...),只需要把标签改成f'Line {idx+1}'就行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:01:18