Python pandas / matplotlib annotating labels above bar chart columns [duplicate]

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

Leave a Comment