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

Discussão em 'Python' iniciado por Stack, Agosto 13, 2025.

  1. Stack

    Stack Membro Participativo

    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:

    [​IMG]

    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.

    Continue reading...

Compartilhe esta Página