S Ringne S Ringne - 26 days ago 9
Python Question

Value on top of a barplot in python

I have a table in pandas df, which has avg_sp and count1 as columns. I plotted a bar graph grouped by ranges and I also added a for loop for the value on top.

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)


But I am not getting the right result, as shown below, it's getting mixed with x axis, is there any way to bring up the no.s a little?

enter image description here

enter image description here

i added the code which pirsquared suggested, but it is affecting only the top bar, and other remain same.

Answer

consider the series 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


same solution with 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


I messed with the height settings a bit to get it where I'd like

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