Home  >  Article  >  Backend Development  >  How to create a grouped bar chart with correct spacing and accurate annotations using Matplotlib and Pandas?

How to create a grouped bar chart with correct spacing and accurate annotations using Matplotlib and Pandas?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 12:23:291039browse

How to create a grouped bar chart with correct spacing and accurate annotations using Matplotlib and Pandas?

Plotting and Annotating a Grouped Bar Chart

Error Analysis

The provided code for creating a grouped bar chart in Python using Matplotlib contains errors. Specifically, the value of w is incorrect, and the annotation placements using autolabel are misaligned.

Corrected w Value:

The value of w should be 0.8 / 3 instead of 0.8 to ensure proper spacing between the bars.

Using Pandas plot for Plotting

A more straightforward approach to plotting a grouped bar chart is to use the plot method of pandas DataFrames. This method allows for easy plotting and annotation.

Improved Annotation Placement

To accurately place annotations above the bars, use the following code:

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')

Here, the offset points are set to (0, 10) to align the annotations directly above the bar centers.

Complete Code

The corrected and improved code is as follows:

import pandas as pd
import matplotlib.pyplot as plt

df = pandas.DataFrame({
    'Very interested': [1332, 1688, 429, 1340, 1263, 1629],
    'Somewhat interested': [729, 444, 1081, 734, 770, 477],
    'Not interested': [127, 60, 610, 102, 136, 74]
    }, index=['Big Data (Spark / Hadoop)', 'Data Analysis / Statistics', 'Data Journalism', 'Data Visualization', 'Deep Learning', 'Machine Learning'])

colors = ['#5cb85c', '#5bc0de', '#d9534f']
fig, ax = plt.subplots(figsize=(20, 8))

ax.set_ylabel('Percentage', fontsize=14)
ax.set_title(
    "The percentage of the respondents' interest in the different data science Area",
    fontsize=16)
ax.set_xticklabels(ax.get_xticklabels(), rotation=0)

df.plot.bar(ax=ax, color=colors)

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')

plt.show()

The above is the detailed content of How to create a grouped bar chart with correct spacing and accurate annotations using Matplotlib and Pandas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn