2
\$\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 !

\$\endgroup\$
  • \$\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\$ – Peilonrayz May 28 '17 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\$ – Yochai May 28 '17 at 15:42
  • \$\begingroup\$ @Peilonrayz I hope it is better now \$\endgroup\$ – Yochai May 28 '17 at 15:48
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.