在python中的barplot顶部的值

时间:2016-11-11 06:03:07

标签: python python-2.7 python-3.x pandas matplotlib

我在pandas df中有一个表,它有avg_sp和count1作为列。我绘制了一个按范围分组的条形图,我还在顶部添加了一个for循环。

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轴混合在一起,有没有办法提出no.s?

enter image description here

enter image description here

我添加了pirsquared建议的代码,但它仅影响顶部栏,而其他代码保持不变。

1 个答案:

答案 0 :(得分:3)

考虑系列imgData.data

s

enter image description here

from matplotlib docs

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

enter image description here

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)

相同的解决方案
ax.patches

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')

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.05*height,
            '%d' % int(height),
            ha='center', va='bottom', rotation=90)

enter image description here