2016-04-26 25 views
6

私は同じプロット上に複数のデータセットをプロットする必要があり、私はmatplotlibを使用します。私はplt.plot()を使用して、私はplt.errorbar()を使用する他の人のためのプロットのいくつかについては凡例プロットPythonで注文

。しかし、私が伝説を作ったときには、最初に、どのような順序でファイルに入れても(そして、zorderは伝説の位置に影響を与えないように思われる)、最初に現れます。

はどのように関係なく、私はデータをプロット道の、私は伝説にしたいという順序を与えることができますか?

答えて

13

ax.get_legend_handles_labelsを使用して凡例のハンドルとラベルを取得し、結果リストを並べ替えてax.legendに入力することで、順序を手動で調整できます。そのような:

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

関連する問題