Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all legends from a matplotlib axes with multiple legends?

Given a matplotlib plot with more than one legend, I would like to be able to remove all legends from the plot.

Here is a simple example code to produce a plot with two legends:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Plot some dummy data
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')

# Add two legends
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)

We get a figure with two legends as expected:

Figure with two legends

Now, I want to remove these legends again. Here's what I tried and what does not work:

# The following solution removes only `leg1`, also in reverse order of calls:
leg2.remove()
leg1.remove()

# The following does not remove anything:
ax.get_legend().remove()

# The following throws an error (matplotlib/artist.py:239, ValueError: list.remove(x): x not in list):
for c in ax.get_children():
    if isinstance(c, matplotlib.legend.Legend):
        c.remove()

I would prefer to have a generic solution like the last one, but for the moment, any solution would be highly appreciated.

like image 735
BernhardWebstudio Avatar asked Dec 21 '25 13:12

BernhardWebstudio


2 Answers

When you call ax.legend it

  • Creates a legend
  • Adds the new legend to the axes
  • Removes any existing legend

So after you called ax.legend twice, you have leg2 on the axes, because leg1 was automatically removed. Then you explicitly add both of them again with add_artist, so you have leg1 on there once, and leg2 on there twice.

If you just remove the line

ax.add_artist(leg2)

Then you will have each legend on the axes only once, and can just use the remove method on both of them.

like image 198
RuthC Avatar answered Dec 24 '25 04:12

RuthC


@RuthC already explained why ax.legend() makes problem

but you can also use matplotlib.legend.Legend() instead of ax.legend()

half_len = len(handles) // 2

leg1 = matplotlib.legend.Legend(ax, handles=handles[:half_len], labels=labels[:half_len], loc="upper left")
leg2 = matplotlib.legend.Legend(ax, handles=handles[half_len:], labels=labels[half_len:], loc="lower right")

ax.add_artist(leg1)
ax.add_artist(leg2)

leg2.remove()
leg1.remove()
like image 20
furas Avatar answered Dec 24 '25 03:12

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!