Barnaby Hussey-Yeo
Barnaby Hussey-Yeo

Reputation: 715

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?

Upvotes: 3

Views: 12811

Answers (1)

Anzel
Anzel

Reputation: 20553

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)

Upvotes: 4

Related Questions