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])
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With