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

Matplotlib图例显示异常:预期与实际输出不符问题排查

问题分析与解决

图例显示异常

用户代码:

Rs= [20, 20, 20, 20]
Ls = [20, 30, 40, 50]
times = [t/10.0 for t in range(0,100)]
for R, L in zip(Rs, Ls):
    I = [m.exp((-R/L)*t)-1 for t in times]
    plt.plot(times,I)
    plt.legend(str(L))

预期图例显示20、30、40、50,但实际仅显示5和0,问题根源与解决方法如下:

问题出在哪?

你在循环里每次调用plt.legend(str(L))的方式错误:

  • Matplotlib的legend()如果传入单个字符串,会把这个字符串拆成单个字符作为独立图例项。比如最后一次循环L=50,str(L)是"50",就会被拆成"5"和"0"两个图例条目。
  • 而且每次调用legend()都会覆盖之前的图例设置,所以最后只留下了最后一次拆分的结果。

怎么改?

给你两种靠谱的修正方式:

方式1:给每条曲线加label,最后统一生成图例

这是最常用的做法,在绘图时直接指定标签,最后一次性生成图例:

import matplotlib.pyplot as plt
import math as m

Rs= [20, 20, 20, 20]
Ls = [20, 30, 40, 50]
times = [t/10.0 for t in range(0,100)]
for R, L in zip(Rs, Ls):
    I = [m.exp((-R/L)*t)-1 for t in times]
    plt.plot(times, I, label=str(L))  # 给当前曲线设置标签
plt.legend()  # 最后统一生成所有图例
plt.show()

方式2:先收集所有标签,最后一次性传入

如果不想在绘图时设置label,可以先把所有标签存到列表里,最后一起传给legend():

import matplotlib.pyplot as plt
import math as m

Rs= [20, 20, 20, 20]
Ls = [20, 30, 40, 50]
times = [t/10.0 for t in range(0,100)]
labels = []
for R, L in zip(Rs, Ls):
    I = [m.exp((-R/L)*t)-1 for t in times]
    plt.plot(times, I)
    labels.append(str(L))
plt.legend(labels)  # 传入所有标签的列表
plt.show()

两种方法都能让图例正确显示20、30、40、50这四个条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:16:35