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 !
1 Answer 1
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.
legend
,legendMap
, andh
? It's kinda hard to suggest a better way, when half the variables are left out. :) \$\endgroup\$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\$