2016-01-16 29 views
8

私はPandas DataFrameをプロットし、平均と中央値を示す線を追加しようとしています。以下に見られるように、私は平均のために赤い線を追加していますが、それは表示されません。pandasとmatplotlibを使った棒グラフの上の平均線

5で緑色の線を描こうとすると、x = 190になります。 x値は160,165,170 ...ではなく0,1,2 ...と扱われます。

どのようにx値がx軸の値と一致するように線を描くことができますか?

Jupyterから:

DataFrame plot

全コード:

%matplotlib inline 

from pandas import Series 
import matplotlib.pyplot as plt 

heights = Series(
    [165, 170, 195, 190, 170, 
    170, 185, 160, 170, 165, 
    185, 195, 185, 195, 200, 
    195, 185, 180, 185, 195], 
    name='Heights' 
) 
freq = heights.value_counts().sort_index() 


freq_frame = freq.to_frame() 

mean = heights.mean() 
median = heights.median() 

freq_frame.plot.bar(legend=False) 

plt.xlabel('Height (cm)') 
plt.ylabel('Count') 

plt.axvline(mean, color='r', linestyle='--') 
plt.axvline(5, color='g', linestyle='--') 

plt.show() 
+0

あなたがプロットしているデータのサンプルを投稿できますか? –

+0

データを含む完全なソースが今追加されました。 – oal

答えて

5

あなたのバープロットをプロットするplt.bar(freq_frame.index,freq_frame['Heights'])を使用してください。その後バーはfreq_frame.indexの位置になります。パンダ・イン・ビルド・バー機能では、私が知る限り、バーの位置を指定することはできません。

%matplotlib inline 

from pandas import Series 
import matplotlib.pyplot as plt 

heights = Series(
    [165, 170, 195, 190, 170, 
    170, 185, 160, 170, 165, 
    185, 195, 185, 195, 200, 
    195, 185, 180, 185, 195], 
    name='Heights' 
) 
freq = heights.value_counts().sort_index() 

freq_frame = freq.to_frame() 

mean = heights.mean() 
median = heights.median() 

plt.bar(freq_frame.index,freq_frame['Heights'], 
     width=3,align='center') 

plt.xlabel('Height (cm)') 
plt.ylabel('Count') 

plt.axvline(mean, color='r', linestyle='--') 
plt.axvline(median, color='g', linestyle='--') 

plt.show() 

bar plot

関連する問題