Python pandas / matplotlib annotates labels above column columns

How to add a shortcut to the value displayed above the columns in the bargain 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() 
+8
python matplotlib pandas
source share
2 answers

Grab the axis into which the graph is drawn, and then treat it like a regular matplotlib object. Putting the value above the panel will look something like this:

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

The solution, without accessing the DataFrame, should 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 that you need to play with xy kwarg (2nd argument) to get the desired label position.

Vertical bars

I found this formatting to be the best overall:

 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 stripes:

 ax.annotate("%.2f" % p.get_width(), (p.get_x() + p.get_width(), p.get_y()), xytext=(5, 10), textcoords='offset points') 
+20
source share

All Articles