2016-11-11 96 views
1

我在pandas df中有一個表,它有avg_sp和count1作爲列。我繪製了一個按範圍分組的條形圖,並且我還爲頂部的值添加了一個for循環。python上的barplot上的值

plt.figure(figsize=(12, 6)) 
df2 = df.groupby(pd.cut(df['avg_sp'], range(0, 110,10))).sum() ['count1'].plot(kind='bar') 
plt.xlabel('avg_sp') 
plt.ylabel('browse count') 

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

但我沒有得到正確的結果,如下圖所示,它變得與x軸混合,有沒有什麼辦法,彈出編號S一點點?

enter image description here

enter image description here

我其中加入pirsquared建議的代碼,但它僅影響頂欄,以及其它保持相同。

+0

你的意思是這樣http://stackoverflow.com/questions/25447700/annotate-酒吧,與值上,大熊貓酒吧,陰謀? – lanery

+0

@lanery我想讓這些值垂直傾斜 – Shubham

+0

您可以將參數'rotation = 90'添加到'ax.annotate'。 – lanery

回答

3

考慮一系列s

s = pd.Series(np.random.randn(10000)) 
s.hist() 

enter image description here


from matplotlib docs

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

ax = s.hist() 
for c in ax.containers: 
    autolabel(c) 

enter image description here


ax.patches

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

enter image description here


rotated labels docs

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

enter image description here

相同溶液

我與高度設置弄亂一點得到它,我想

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

enter image description here

+0

和旋轉= 90也可以工作呢?順便說一句,謝謝 – Shubham

+0

@SRingne更新了帖子,歡迎 – piRSquared

+0

在我** barplot **高度變化沒有發生,它幾乎接觸x軸,即使在運行您的編輯後, 只有第一個欄是受影響,剩餘酒吧距離仍然相同 – Shubham