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

如何将Pandas DataFrame列名用作图例标签,无需手动指定?

直接用DataFrame列名作为Matplotlib图例标签的方法

当然可以不用手动指定图例标签,直接调用DataFrame的列名来自动生成,下面是两种实用的实现方式:

方法一:用Pandas内置的plot方法直接绘制

Pandas的DataFrame自带的plot方法会自动把列名作为图例标签,不管你是绘制全部列还是指定单列,都不需要手动写标签:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(data={'col1': [0, 2, 1, 3], 
                        'col2': [9,7,8,9]}, 
                        index=[0, 1, 2, 3])

f = plt.figure()
ax = f.subplots()

# 绘制单列,自动用列名作为标签
df[['col1']].plot(ax=ax)
# 如果要绘制多列,直接写df.plot(ax=ax)即可,所有列名都会自动作为标签

ax.legend()
plt.show()

方法二:提取列的name属性手动传入label参数

如果坚持用Matplotlib的ax.plot方法单独绘制某一列,可以直接获取列的name属性作为标签值,避免手动写字符串:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(data={'col1': [0, 2, 1, 3], 
                        'col2': [9,7,8,9]}, 
                        index=[0, 1, 2, 3])

f = plt.figure()
ax = f.subplots()

# 用列的name属性自动填充label
ax.plot(df['col1'], label=df['col1'].name)

ax.legend()
plt.show()

这两种方法都能帮你省去手动输入列名的麻烦,尤其是列名较长或者需要批量绘制时,用第一种方法效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:35:26