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

如何让Matplotlib图例显示列表名称而非列表本身的内容

解决Matplotlib图例显示变量名而非变量值的方法

你当前的代码直接将x、y两个变量存入列表m,遍历时只能读取到变量的实际数值,无法获取变量的原始名称字符串,因此图例只会渲染列表的具体内容。

  • 方法1:手动绑定变量名与变量值(最推荐)
    该方法兼容性最强、可控性最高,不会出现匹配错误的问题。只需将原列表改为存储「变量名字符串、变量值」的二元组结构即可,修改后的完整代码如下:
import numpy as np
import matplotlib.pyplot as plt

# 提前定义x、y两个变量
x = np.random.rand(10)
y = np.random.rand(10)

# 修改列表结构,成对存储变量名和对应值
m = [("x", x), ("y", y)]
fig = plt.figure()
ax = plt.subplot(111)

# 遍历同时取出变量名和变量值
for var_name, var_value in m:
    ax.plot(var_value, label=f'$variable = {var_name}$')

# 原有布局、图例逻辑保持不变
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()
  • 方法2:动态匹配变量名(仅适合特定场景)
    如果不想手动输入变量名字符串,可以通过全局/局部变量字典匹配值对应的变量名,该方法仅适合单值对应唯一变量的全局作用域场景,代码示例如下:
import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(10)
y = np.random.rand(10)
m = [x, y]

fig = plt.figure()
ax = plt.subplot(111)

for var_value in m:
    # 从全局变量中匹配当前值对应的变量名
    var_name = [k for k, v in globals().items() if v is var_value][0]
    ax.plot(var_value, label=f'$variable = {var_name}$')

box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

你当前输出的效果参考:
当前输出效果图
修改后图例将按需求显示variable = x和variable = y。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:18:02