2016-10-16 139 views
1
df = { 'id' : pd.Series([1,1,1,1,2,2,2,2,3,3,4,4,4])} 

num_id = df['id'].value_counts().hist(bins=2) 

我得到一個很好的直方圖,並計入每個bin中的id數。熊貓註釋數據幀直方圖

問題是,我如何向每個欄添加註釋以顯示計數?它可能在白色文字的中間。

我知道有一個ax參數,我們可以在hist()中指定,但我不知道如何。

enter image description here

+0

['ax.text'](http://matplotlib.org/ users/text_intro.html)是你需要的。您可以將x和y座標綁定到bin邊緣'hist'返回... – Kartik

+0

您能說明一下嗎? – jxn

回答

1

給您(與import陳述,以防萬一):

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.DataFrame({ 'id' : [1,1,1,1,2,2,2,2,3,3,4,4,4]}) 

fig, ax = plt.subplots() 
freq, bins, _ = ax.hist(df['id'].value_counts(), 2, facecolor='skyblue') 
ax.grid(True) 
for i, n in enumerate(freq): 
    ax.text(bins[i]+0.5, 2, n) 
ax.set_xlabel('Bins') 
ax.set_ylabel('Freq') 
plt.show() 

Histogram, with Text