2016-11-27 7 views
0

凡例に表示されるBollinger Bands( 'upper band'、 'rolling mean'、 'lower band')のラベルが必要です。しかし、凡例は、最初の(唯一の)列である「IBM」のパンダ・ラベルを付けて、各行に同じラベルを適用するだけです。4行のpython/matlibplotを使って凡例を生成できません。

# Plot price values, rolling mean and Bollinger Bands (R) 
ax = prices['IBM'].plot(title="Bollinger Bands") 
rm_sym.plot(label='Rolling mean', ax=ax) 
upper_band.plot(label='upper band', c='r', ax=ax) 
lower_band.plot(label='lower band', c='r', ax=ax) 
# 
# Add axis labels and legend 
ax.set_xlabel("Date") 
ax.set_ylabel("Adjusted Closing Price") 
ax.legend(loc='upper left') 
plt.show() 

私は、このコードはmatlibplotは説明は特に歓迎されているので、どのように動作するかの理解の基本的な不足を表すことができる知っています。

+0

'plt.legend(loc = '左上')' – mikeqfu

答えて

0

upper_bandlower_bandが何であっても、問題はおそらくそれにラベル付けされていません。

1つのオプションは、列としてデータフレームに配置することによってラベルを付けることです。これにより、dataframe列を直接プロットすることができます。

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

y =np.random.rand(4) 
yupper = y+0.2 
ylower = y-0.2 

df = pd.DataFrame({"price" : y, "upper": yupper, "lower": ylower}) 

fig, ax = plt.subplots() 
df["price"].plot(label='Rolling mean', ax=ax) 
df["upper"].plot(label='upper band', c='r', ax=ax) 
df["lower"].plot(label='lower band', c='r', ax=ax) 

ax.legend(loc='upper left') 
plt.show() 

また、データを直接プロットすることもできます。

import matplotlib.pyplot as plt 
import numpy as np 

y =np.random.rand(4) 
yupper = y+0.2 
ylower = y-0.2 

fig, ax = plt.subplots() 
ax.plot(y,  label='Rolling mean') 
ax.plot(yupper, label='upper band', c='r') 
ax.plot(ylower, label='lower band', c='r') 

ax.legend(loc='upper left') 
plt.show() 

どちらの場合でも、ラベル付きの凡例が表示されます。これで十分でない場合は、Matplotlib Legend Guideを読むことをお勧めします。これは、凡例に手動でラベルを追加する方法も示しています。

関連する問題