Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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]) 
like image 839
CPBL Avatar asked Mar 08 '14 01:03

CPBL


People also ask

How do I change the order of items in Matplotlib legend?

Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.

How do I specify the position of legend in Matplotlib?

A legend is an area describing the elements of the graph. In the matplotlib library, there's a function called legend() which is used to Place a legend on the axes. The attribute Loc in legend() is used to specify the location of the legend. Default value of loc is loc=”best” (upper left).

How do I move my legend to the right in Matplotlib?

Matplotlib legend outside plot right To set the location to right, we pass the loc parameter to the legend() method. The value of loc could be a number or a string. The number value to set right is 5 and the string value is right.


1 Answers

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

like image 112
kevin Avatar answered Sep 29 '22 19:09

kevin