"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create and Annotate a Grouped Bar Chart Using Matplotlib in Python?

How to Create and Annotate a Grouped Bar Chart Using Matplotlib in Python?

Published on 2024-11-10
Browse:566

How to Create and Annotate a Grouped Bar Chart Using Matplotlib in Python?

How to Plot and Annotate a Grouped Bar Chart

Plotting a grouped bar chart with Python's Matplotlib requires careful consideration of data manipulation, bar spacing, and labeling. Here's how to address your specific issue:

Data Preparation

  • Instead of dividing each column by 2233 separately, use the div() method on the entire df to achieve the same effect in a single line: df = df.div(2233).

Pre-matplotlib 3.4.2

  • Adjust the w value to 0.8 / 3 to correctly space the bars.

Post-matplotlib 3.4.2

  • Utilize matplotlib.pyplot.bar_label and pandas.DataFrame.plot for a simpler and more elegant approach.

Annotation

  • To label the bars, use the annotate() function within a loop that iterates over the patches.
  • Adjust the positioning of the annotations based on the desired alignment and aesthetics.

Sample Code

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(...).div(2233)

ax = df.plot(kind='bar', color=colors, figsize=(20, 8), ylabel='Percentage', title="...")

for p in ax.patches:
    ax.annotate(f'{p.get_height():0.2f}', (p.get_x()   p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')

This code will generate a grouped bar chart with annotated bar heights.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3