matplotlib get_legend_handles_labels always return empty

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 !

• Just wondering, what are legend, legendMap, and h? It's kinda hard to suggest a better way, when half the variables are left out. :) – Peilonrayz May 28 '17 at 13:09
• 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. – Yochai May 28 '17 at 15:42
• @Peilonrayz I hope it is better now – Yochai May 28 '17 at 15:48

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