Pandas: How to Annotate Bars in Bar Plot


You can use the following methods to annotate bars in a pandas bar plot:

Method 1: Annotate Bars in Simple Bar Plot

ax = df.plot.bar()

ax.bar_label(ax.containers[0])

Method 2: Annotate Bars in Grouped Bar Plot

ax = df.plot.bar()

for container in ax.containers:
    ax.bar_label(container)

The following examples show how to use each method in practice.

Example 1: Annotate Bars in Simple Bar Plot

The following code shows how to annotate bars in a simple bar plot:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'product': ['A', 'B', 'C', 'D', 'E'],
                   'sales': [4, 7, 8, 15, 12]})

#view DataFrame
print(df)

  product  sales
0       A      4
1       B      7
2       C      8
3       D     15
4       E     12

#create bar plot to visualize sales by product
ax = df.plot.bar(x='product', y='sales', legend=False)

#annotate bars
ax.bar_label(ax.containers[0])

pandas annotate bar plot

Notice that the actual value for the sales is shown at the top of each bar.

Example 2: Annotate Bars in Grouped Bar Plot

The following code shows how to annotate bars in a grouped bar plot:

#create DataFrame
df = pd.DataFrame({'productA': [14, 10],
                   'productB': [17, 19]},
                    index=['store 1', 'store 2'])

#view DataFrame
print(df)

         productA  productB
store 1        14        17
store 2        10        19

#create grouped bar plot
ax = df.plot.bar()

#annotate bars in bar plot
for container in ax.containers:
    ax.bar_label(container)

pandas annotate bars in grouped bar plot

Notice that annotations have been added to each individual bar in the plot.

Additional Resources

The following tutorials explain how to create other common visualizations in pandas:

How to Create Boxplot from Pandas DataFrame
How to Create Pie Chart from Pandas DataFrame
How to Create Histogram from Pandas DataFrame

Leave a Reply

Your email address will not be published.