2017-10-24 10 views
2

凡例のテキストがプロットバーと同じ順序になっていないことに気がつきました。私は伝説の最初の場所で "バナナ"を見ることが期待されます。このような動作を修正することは可能ですか?おかげbarplotはmatplotlibの凡例のテキストの順序を尊重しません

私のコードは次のとおりです。

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.DataFrame({"Apple" : [2,3,4,1], "Banana" : [4,2,1,2]}) 

ax = df.plot.barh() 
ax.legend() 

plt.show() 

そして、私のグラフ:

enter image description here

答えて

2

は凡例ラベルが実際に正しく順序付けられています。 Matplotlibの垂直軸は、デフォルトで底部から始まり、上方に向かっています。したがって、伝説のように青いバーが最初に来ます。

あなたは伝説のハンドルやラベルを反転することができます

h, l = ax.get_legend_handles_labels() 
ax.legend(h[::-1], l[::-1]) 

ます。また、y軸を反転することもできます。伝説ハンドラの

ax = df.plot.barh() 
ax.invert_yaxis() 

enter image description here

2

注文は注文の列で選択されている、あなたは逆の順序(列軸に使用reindex_axis)にデータフレームの列の名前を並べ替える必要があります。

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.DataFrame({"Apple" : [2,3,4,1], "Banana" : [4,2,1,2]}) 
df = df.reindex_axis(reversed(sorted(df.columns)), axis = 1) 
ax = df.plot.barh() 
ax.legend() 

plt.show() 

enter image description here

関連する問題