2016-11-16 7 views
0

私のパンダのテーブルにテーブルがあります。トップパイソンの値を棒グラフでプロット

Total_orders frequency 
     0.0   18679137 
     1.0   360235 
     2.0   68214 
     3.0   20512 
     4.0   7211 
     ...   ... 
     50.0   12 

私は棒グラフの総注文数と頻度をプロットしたいと思います。頻度の値は各バーの上部に表示されます。

私はこれら3つのコードを実行しています。

CODE1:

plt.figure(figsize=(12,6)) 
df2 = df.groupby('Total_orders')['frequency'].plot(kind='bar') 
plt.xlabel('Total_orders') 
plt.ylabel('frequency') 

for rect in df2.patches: 
    height = rect.get_height() 
    df2.text(rect.get_x() + rect.get_width()/2., 1.05*height+100, 
'%d' % int(height),ha='center', va='bottom', rotation=90) 

CODE2:

for ii,rect in enumerate(df2.patches): 
    height = rect.get_height() 
    df2.text(rect.get_x() + rect.get_width()/2., 1.14*height+100,'%d' % int(height),ha='center', va='bottom', rotation=90) 

CODE3

for p in df2.patches: 
df2.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() *1.05),rotation=90) 

が、私は、それは私にエラーを示すのコードを実行しているのです

(ループ用)

AttributeError: 'Series' object has no attribute 'patches'

これがなぜ起こっているのか、どのように削除するのか、ご存じですか?

+1

が見えます'patches'属性はありません。あなたは反復したい 'patches'を持つオブジェクトにアクセスする方法を見つけなければなりません。 –

答えて

1

はこれを試してみてください(? `df2`)あなたは` Series`オブジェクトにアクセスし、その `patches`が、` Series`オブジェクトを反復処理しようとしているよう

def autolabel(rects, height_factor=1.05): 
    # attach some text labels 
    for rect in rects: 
     height = rect.get_height() 
     ax.text(rect.get_x() + rect.get_width()/2., height_factor*height, 
       '%d' % int(height), 
       ha='center', va='bottom') 


In [48]: df 
Out[48]: 
    Total_orders frequency 
0   0.0 18679137 
1   1.0  360235 
2   2.0  68214 
3   3.0  20512 
4   4.0  7211 
5   50.0   12 

In [49]: import matplotlib 

In [50]: matplotlib.style.use('ggplot') 

In [51]: ax = df.plot.bar(x='Total_orders', y='frequency', rot=0, width=0.85, alpha=0.6, figsize=(14,12)) 

In [52]: autolabel(ax.patches, 1.02) 

enter image description here

+0

私は値の高さを上げることができます。つまり、図に示すようにx軸に非常に近いことを意味します。ちょっと(約0.5cm)上がりたいので、プロットが素敵です。 – Shubham

+0

@SRingne、確かに 'height_factor'パラメータを高く設定してください。 – MaxU

+0

diid、さらに5まで増やしました、' height_factor * height + 100'でも変更はありませんでした – Shubham

関連する問題