Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding datalabels - matplotlib barchart

I have a pandas DataFrameGroupBy object that I am ploting like so...

grouped.sum().plot(kind='bar')

which gives...

enter image description here

but I would like something more like this...

enter image description here

I just want to know how to add data labels to each column and possibly a table as well?

like image 404
Barnaby Hussey-Yeo Avatar asked Mar 18 '26 11:03

Barnaby Hussey-Yeo


1 Answers

To add value labels on top of the bar plot, you can loop through the columns in each index and use text to show the values, something like this:

df = DataFrame(rand(3,2), columns=['A', 'B'])
ax = df.plot(table=True, kind='bar', title='Random')
for i, each in enumerate(df.index):
    for col in df.columns:
        y = df.ix[each][col]
        ax.text(i, y, y)

You may want to adjust the text labels coords to have a better alignment etc.


To show the grid table, pandas has table support from 0.14+.

You can read more about Plotting table HERE

Plotting with matplotlib table is now supported in DataFrame.plot() and Series.plot() with a table keyword. The table keyword can accept bool, DataFrame or Series. The simple way to draw a table is to specify table=True. Data will be transposed to meet matplotlib’s default layout.

fig, ax = plt.subplots(1, 1)
df = DataFrame(rand(5, 3), columns=['a', 'b', 'c'])
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=True, ax=ax)

Also, you can pass different DataFrame or Series for table keyword. The data will be drawn as displayed in print method (not transposed automatically). If required, it should be transposed manually as below example.

fig, ax = plt.subplots(1, 1)
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=np.round(df.T, 2), ax=ax)
like image 140
Anzel Avatar answered Mar 20 '26 00:03

Anzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!