Find out if a line is part of a legend

Viewed 92

I have a matplotlib plot and I would like to find out which lines have set a label. Calling get_label() on the lines works, but also gives a non-empty result if the label is not set, e.g.,

import matplotlib as mpl
import matplotlib.pyplot as plt

plt.plot([0.0], [0.0], label="test 1")
plt.plot([0.0], [0.0], label="test 2")
plt.plot([0.0], [0.0])  # no label


lines = []
for child in plt.gca().get_children():
    if isinstance(child, mpl.lines.Line2D):
        print(child.get_label())
test 1
test 2
_line2  # !

Any hints?

1 Answers

The "empty" labels all start with an underscore. You can even explicitly set a label starting with an underscore to have an informative label for other purposes but not having it show up in the legend.

From the docs:

Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists.

And the legend tutorial:

Those artists with an empty string as label or with a label starting with "_" will be ignored.

Related