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

如何在直接使用Pandas绘图时抑制指定图例条目?

Pandas+Matplotlib 绘图时控制图例显示的问题

问题场景

我需要在Matplotlib的坐标轴ax上多次调用Pandas DataFrame的plot方法(df.plot(..., ax=ax))完成绘图,但希望部分曲线不生成图例条目。尝试添加label="_nolegend_"并未生效,目前只能手动提取数据后循环调用ax.plot来按需设置label,操作十分繁琐。(注:并非要完全移除图例)

特殊复现情况

尝试了文档中推荐的方法但无效,怀疑问题和绘制的曲线数量有关,复现代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dg = pd.DataFrame(data=np.random.rand(400).reshape(10,40))
fig1, ax = plt.subplots(figsize=(12, 4))
# 这部分浅灰色曲线不需要图例
dg.iloc[1:8].plot(ax=ax,style='.-',color='lightgray',legend=False)
# 这两条曲线需要显示图例
dg[[32,33]].iloc[1:8].plot(ax=ax)

使用Matplotlib 3.5.1和Pandas 1.4.2时,结果不稳定,有时生成的图表完全没有图例。

可行解决方案

针对这个版本兼容问题,提供两种简洁的处理方式:

方法1:绘图后手动筛选并重建图例

先完成所有绘图操作,再获取图例的手柄和标签,筛选出需要保留的部分重新生成图例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dg = pd.DataFrame(data=np.random.rand(400).reshape(10,40))
fig1, ax = plt.subplots(figsize=(12, 4))
# 绘制所有曲线,包括不需要图例的部分
dg.iloc[1:8].plot(ax=ax,style='.-',color='lightgray')
dg[[32,33]].iloc[1:8].plot(ax=ax)

# 筛选需要保留的图例条目(仅保留标签为32、33的曲线)
handles, labels = ax.get_legend_handles_labels()
keep_indices = [i for i, label in enumerate(labels) if label in ['32', '33']]
filtered_handles = [handles[i] for i in keep_indices]
filtered_labels = [labels[i] for i in keep_indices]

# 重新生成图例
ax.legend(filtered_handles, filtered_labels)

方法2:批量设置曲线的_nolegend_标签

先绘制不需要图例的曲线,然后批量修改这些曲线的标签为_nolegend_,Matplotlib会自动忽略这些条目:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dg = pd.DataFrame(data=np.random.rand(400).reshape(10,40))
fig1, ax = plt.subplots(figsize=(12, 4))
# 绘制浅灰色曲线,并获取所有线条对象
ax_lines = dg.iloc[1:8].plot(ax=ax,style='.-',color='lightgray').get_lines()
# 批量设置标签为_nolegend_
for line in ax_lines:
    line.set_label("_nolegend_")
# 绘制需要显示图例的曲线
dg[[32,33]].iloc[1:8].plot(ax=ax)
# 自动过滤不需要的图例条目
ax.legend()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:27:33