Duplicate items in legend in matplotlib?

user2881553

I am trying to add the legend to my plot with this snippet:

import matplotlib.pylab as plt

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.set_xlabel('x (m)')
axes.set_ylabel('y (m)')
for i, representative in enumerate(representatives):
    axes.plot([e[0] for e in representative], [e[1] for e in representative], color='b', label='Representatives')
axes.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r', label='Intersections')
axes.legend()   

I end up with this plot

enter image description here

Obviously, the items are duplicated in the plot. How can I correct this error?

DSM

As the docs say, although it's easy to miss:

If label attribute is empty string or starts with “_”, those artists will be ignored.

So if I'm plotting similar lines in a loop and I only want one example line in the legend, I usually do something like

ax.plot(x, y, label="Representatives" if i == 0 else "")

where i is my loop index.

It's not quite as nice to look at as building them separately, but often I want to keep the label logic as close to the line drawing as possible.

(Note that the matplotlib developers themselves tend to use "_nolegend_" to be explicit.)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related