Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order in legend plots python

I need to plot multiple sets of data on the same plot, and I use matplotlib.

For some of plots I use plt.plot() and for the others I use plt.errorbar(). But when I make a legend the ones created with plt.plot() appears first, no matter in which order I put them in the file (and zorder seems to have no effect on the position in the legend).

How can I give the order that I want in the legend, regardless of the way I plot the data?

like image 550
Silviu Avatar asked Apr 26 '16 13:04

Silviu


1 Answers

You can adjust the order manually, by getting the legend handles and labels using ax.get_legend_handles_labels, and then reordering the resulting lists, and feeding them to ax.legend. Like so:

import matplotlib.pyplot as plt
import numpy as np

fig,ax = plt.subplots(1)

ax.plot(np.arange(5),np.arange(5),'bo-',label='plot1')
ax.errorbar(np.arange(5),np.arange(1,6),yerr=1,marker='s',color='g',label='errorbar')
ax.plot(np.arange(5),np.arange(2,7),'ro-',label='plot2')

handles,labels = ax.get_legend_handles_labels()

handles = [handles[0], handles[2], handles[1]]
labels = [labels[0], labels[2], labels[1]]

ax.legend(handles,labels,loc=2)
plt.show()

enter image description here

like image 62
tmdavison Avatar answered Oct 20 '22 08:10

tmdavison