12

How do I add the label for the value to display above the bars in the bargraph here:

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'Users': [ 'Bob', 'Jim', 'Ted', 'Jesus', 'James'],
                 'Score': [10,2,5,6,7],})

df = df.set_index('Users')
df.plot(kind='bar',  title='Scores')

plt.show()
Kamil Sindi
  • 19,100
  • 18
  • 89
  • 115
ccsv
  • 7,248
  • 11
  • 47
  • 86

2 Answers2

39

A solution without accessing the DataFrame is to use the patches attribute:

ax = df.plot.bar(title="Scores")
for p in ax.patches:
    ax.annotate(str(p.get_height()), xy=(p.get_x(), p.get_height()))

Note you have to play around with the xy kwarg (2nd arg) to get the label position you desire.

Vertical Bars

I found this formatting to be the best in general:

ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

Horizontal Bars

I found the following format to work well with horizontal bars:

ax.annotate("%.2f" % p.get_width(), (p.get_x() + p.get_width(), p.get_y()), xytext=(5, 10), textcoords='offset points')
Kamil Sindi
  • 19,100
  • 18
  • 89
  • 115
  • Hey Kamil. I tried this solution and could get the annotations on the chart. However, they turned out to be in reverse order for my stacked bar chart. It is a single bar with three stacks [10%,30%,60%]. The annotations came as [60%,30%,10%]. I couldn't understand why. Can you suggest something? – Meet Mar 05 '21 at 17:55
  • And about line graphs? – Lucas Brito Mar 02 '22 at 19:56
17

Capture the axis where the plot is drawn into, then manipulate it as a usual matplotlib object. Putting the value above the bar will be something like this:

ax = df.plot(kind='bar',  title='Scores', rot=0)
ax.set_ylim(0, 12)
for i, label in enumerate(list(df.index)):
    score = df.loc[label]['Score']
    ax.annotate(str(score), (i, score + 0.2))

enter image description here

Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113
joemar.ct
  • 1,196
  • 8
  • 14