5
\$\begingroup\$

I have a problem when adding elements to the same figure. The problem is with the legend. At each iteration I add elements and the corresponding legend. But I want the legend to include all the different elements from all iterations.

The problem is that the function get_legend_handles_labels() returns empty handles & labels lists.

The code is as follows:

 handles, labels = ax.get_legend_handles_labels()
 for key in legendMap.iterkeys():
 if key not in labels:
 handles.append(h[legendMap[key]])
 labels.append(key)
 ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5))
 h1,l1 = ax.get_legend_handles_labels()

h1, l1 are empty rather being the same as handles, labels

The following code does the trick, but I believe there should be more elegant solution:

 legend = ax.get_legend()
 labels = [] if legend is None else [str(x._text) for x in legend.texts]
 handles = [] if legend is None else legend.legendHandles
 for key in legendMap.iterkeys():
 if key not in labels:
 handles.append(h[legendMap[key]])
 labels.append(key)
 ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5))

Help is much appreciated, thanks !

Peilonrayz
44.4k7 gold badges80 silver badges157 bronze badges
asked May 28, 2017 at 9:05
\$\endgroup\$
3
  • \$\begingroup\$ Just wondering, what are legend, legendMap, and h? It's kinda hard to suggest a better way, when half the variables are left out. :) \$\endgroup\$ Commented May 28, 2017 at 13:09
  • \$\begingroup\$ legend is the sub-plot legend element: legend = ax.get_legend() h = ax.barh(...) legendMap is a map between item that was added to the plot to its index, in order to add it to the legend. \$\endgroup\$ Commented May 28, 2017 at 15:42
  • \$\begingroup\$ @Peilonrayz I hope it is better now \$\endgroup\$ Commented May 28, 2017 at 15:48

1 Answer 1

2
\$\begingroup\$

When you adding curves, bar to your chart specify label, like:

ax.plot(x, y, linewidth=1.75, color='#00ff00', label='curve1')

After that everything works like a charm.

answered May 28, 2018 at 12:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.