How is order of items in matplotlib legend determined?
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])
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