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

如何移除Matplotlib坐标轴上的所有多个图例?

移除Matplotlib绘图中的所有图例

问题场景

我需要移除Matplotlib绘图里的所有图例,先看生成带有两个图例的示例代码:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# 生成测试数据
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [25, 16, 9, 4, 1]
ax.plot(x, y1, label='y = x^2')
ax.plot(x, y2, label='y = 25 - x^2')

# 添加两个图例
ax.legend()

handles, labels = ax.get_legend_handles_labels()

ax.get_legend().remove()

half_len = len(handles) // 2
leg1 = ax.legend(handles[:half_len], labels[:half_len], loc="upper left")
leg2 = ax.legend(handles[half_len:], labels[half_len:], loc="lower right")
ax.add_artist(leg1)
ax.add_artist(leg2)

这段代码会生成一个带有两个图例的绘图,现在需要移除这两个图例,但之前尝试的几种方法都无效:

  • 先调用leg2.remove()再调用leg1.remove(),只能移除leg1
  • ax.get_legend().remove()完全不起作用
  • 遍历ax.get_children()移除图例时,会抛出ValueError: list.remove(x): x not in list错误

解决方案

方法一:按正确顺序操作已保存的图例对象

因为leg2是最后创建的,它会被设为轴的"主图例"(ax.legend_指向它),所以必须先移除leg2,再移除leg1,这样两个图例都会被正确移除:

# 正确移除顺序
leg2.remove()
leg1.remove()

方法二:通用遍历移除方案(推荐)

之前遍历报错是因为在遍历get_children()返回的列表时直接修改它,导致元素丢失。可以先把所有图例对象收集到一个独立列表,再逐个移除:

import matplotlib.legend

# 先收集所有图例对象
all_legends = [child for child in ax.get_children() if isinstance(child, matplotlib.legend.Legend)]
# 逐个移除
for legend in all_legends:
    legend.remove()

方法三:分别处理主图例和艺术家图例

Matplotlib中,图例分为两种:轴的主图例(ax.legend_)和通过add_artist()添加的图例,我们可以分别处理:

import matplotlib.legend

# 移除主图例
if ax.legend_ is not None:
    ax.legend_.remove()

# 移除所有作为艺术家添加的图例
for artist in list(ax.artists):
    if isinstance(artist, matplotlib.legend.Legend):
        artist.remove()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 12:42:49