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 &amp; 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 !
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.