2017-11-22 8 views
1

私は、凡例が最新の観測のランキングによって決定される単純なバンプチャートを作成しようとしています。私はpandas DataFrame "y"のように見える行間のランキングを持っています。matplotlibの凡例のアイテムを動的に並べ替える方法は?

In[231]: y 
Out[231]: 
Currency AUD CAD CHF EUR GBP JPY NOK NZD SEK USD 
2017-09-08 5.0 1.0 8.0 3.0 9.0 7.0 4.0 6.0 2.0 10.0 
2017-09-22 8.0 2.0 10.0 1.0 5.0 9.0 4.0 6.0 3.0 7.0 
2017-10-06 4.0 5.0 10.0 2.0 7.0 9.0 3.0 8.0 1.0 6.0 
2017-10-20 3.0 4.0 10.0 1.0 7.0 5.0 6.0 9.0 2.0 8.0 
2017-11-03 5.0 3.0 10.0 1.0 9.0 7.0 2.0 8.0 4.0 6.0 
2017-11-17 5.0 4.0 10.0 1.0 9.0 7.0 3.0 8.0 2.0 6.0 

私がこれまで使用しているコード:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 

fig = plt.figure(figsize=(8.5,8.5)) 
ax = fig.add_subplot(111) 

l1,l2,l3,l4,l5,l6,l7,l8,l9,l10 = ax.plot_date(y.index.to_pydatetime(), y, '*-') 
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=(4),interval=2)) 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) 
ax.yaxis.set_ticks(np.arange(1, 11, 1)) 
ax.set_title('Sample Chart', fontsize=20) 
plt.gca().invert_yaxis() 
fig.legend([l1,l2,l3,l4,l5,l6,l7,l8,l9,l10], ['AUD','CAD','CHF','EUR','GBP','JPY','NOK','NZD','SEK','USD'], 'right', fontsize=16, frameon=False, labelspacing=1.4) 
plt.tight_layout(pad=10) 

fig.png

の出力を生成し、私の質問は、2017年「からの最後の観察に基づいて凡例を並べ替える方法です-11-17 '?つまり、私はEUR、SEK、NOKなどが必要です。静的なアルファベット順は望ましくありません。基本的にfig.legendでは[l4、l9、l7、...、l3]が必要ですが、このリストは 'y'に行が追加されるときに並べ替えられます。私は簡単に順序を適切に並べ替えてリストを生成することができますが、fig.legendは要素が引用符で囲まれたリストを受け付けません。['l4'、 'l9'、 'l7'、...、 'l3']

私はこれを完全に間違っている可能性がありますので、どんな助けも素晴らしいでしょう。

答えて

0

凡例のハンドルとして使用する行のリストと、データフレームの最後の(または他の)行の並べ替えの結果によるラベルのリストを並べ替える必要があります。

lines = ax.plot_date(...) 
lastrow = y.iloc[-1,:].values 
order = np.argsort(lastrow) 
fig.legend(np.array(lines)[order], y.columns[order]) 

コンプリート例:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 

fig, ax = plt.subplots(figsize=(6.4,3)) 

lines = ax.plot_date(y.index.to_pydatetime(), y, '*-') 
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=(4),interval=2)) 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) 
ax.yaxis.set_ticks(np.arange(1, 11, 1)) 

plt.gca().invert_yaxis() 

lastrow = y.iloc[-1,:].values 
order = np.argsort(lastrow) 
fig.legend(np.array(lines)[order], y.columns[order], loc='right', frameon=False) 
plt.subplots_adjust(right=0.85) 
plt.show() 

enter image description here

+0

完璧に動作します、ありがとう! – RHoward

関連する問題