How is order of items in matplotlib legend determined?

CPBL picture CPBL · Mar 8, 2014 · Viewed 55.8k times · Source

I am having to reorder items in a legend, when I don't think I should have to. I try:

from pylab import *
clf()
ax=gca()
ht=ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.1))
h1=ax.bar(1,2,label='Middle')
hb=ax.add_patch(Rectangle((1,1),1,1,color='k',label='Bottom',alpha=.11))
legend()
show()

and end up with Bottom above Middle. How can I get the right order? Is it not determined by creation order?

Code results in wrong legend item order

Update: The following can be used to force the order. I think this may be the simplest way to do it, and that seems awkward. The question is what determines the original order?

hh=[ht,h1,hb]
legend([ht,h1.patches[0],hb],[H.get_label() for H in hh])

Answer

kevin picture kevin · Dec 16, 2014

Here's a quick snippet to sort the entries in a legend. It assumes that you've already added your plot elements with a label, for example, something like

ax.plot(..., label='label1')
ax.plot(..., label='label2')

and then the main bit:

handles, labels = ax.get_legend_handles_labels()
# sort both labels and handles by labels
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
ax.legend(handles, labels)

This is just a simple adaptation from the code listed at http://matplotlib.org/users/legend_guide.html