How is order of items in matplotlib legend determined? How is order of items in matplotlib legend determined? python python

How is order of items in matplotlib legend determined?


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 labelslabels, 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


A slight variation on some other aswers. The list order should have the same length as the number of legend items, and specifies the new order manually.

handles, labels = plt.gca().get_legend_handles_labels()order = [0,2,1]plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])


The order is deterministic, but part of the private guts so can be changed at any time, see the code here (the self.* elements are lists of the artists that have been added, hence the handle list is sorted first by type, second by order they were added).

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.