["python","matplotlib","legend"]
How is order of items in matplotlib legend determined?

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? 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])
The order is deterministic, but part of the private guts so can be changed at any time, see the code here which goes to here and eventually here. The children are the artists that have been added, hence the handle list is sorted by order they were added (this is a change in behavior with mpl34 or mpl35). If you want to explicitly control the order of the elements in your legend then assemble a list of handlers and labels like you did in the your edit.