18.4 C
London
Saturday, July 19, 2025
HomePandas in PythonGeneral Functions in PythonPandas: How to Annotate Bars in Bar Plot

Pandas: How to Annotate Bars in Bar Plot

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories