Monday, 5 April 2021

Roundtrip legend

Here's a little code snippet:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.errorbar([1, 2, 3], [1, 1, 1], yerr=[.1, .1, .1], c='orange', label='orange')
ax.legend()
ax.plot([1, 2, 3], [2, 2, 2], c='blue', label='blue')
leg = ax.get_legend()

It looks like this:

enter image description here

Now, if I was given leg, how could I recreate the legend?

I have tried

ax.legend(leg.legendHandles, [i.get_text() for i in leg.get_texts()])

However, this doesn't preserve the maker info (notice how now the line in the legend is just a straight line, rather than a line with an error bar through it)

enter image description here

I have also tried

ax.legend(*ax.get_legend_handles_labels());

however this adds a new line which wasn't visible in the original legend.

enter image description here


EDIT

If the original plot was

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.errorbar([1, 2, 3], [1, 1, 1], yerr=[.1, .1, .1], c='orange', label='orange')
ax.plot([1, 2, 3], [3, 3, 3], c='green', label='green')
ax.legend()
ax.plot([1, 2, 3], [2, 2, 2], c='blue', label='blue')
leg = ax.get_legend()

, which looks like this: enter image description here

then I would want to keep both the orange and the green lines. Basically, I want to keep only what's already visible in the legend, while ax.get_legend_handles_labels gives me everything back.

EDIT2

A 1-1 mapping between leg.legendHandles and ax.get_legend_handles_labels() would allow for this to be accomplished, can that be done?



from Roundtrip legend

No comments:

Post a Comment