Home > Backend Development > Python Tutorial > How to Center Data Labels in a Matplotlib Stacked Bar Chart?

How to Center Data Labels in a Matplotlib Stacked Bar Chart?

DDD
Release: 2024-11-24 00:41:10
Original
483 people have browsed it

How to Center Data Labels in a Matplotlib Stacked Bar Chart?

Stacked Bar Chart with Centered Labels: An Improved Solution Using bar_label

In matplotlib, a refined method for accurately centering data labels in a stacked bar chart is available using the bar_label function. Here's how it's done:

  1. Import necessary modules: Begin by importing the essential libraries.
import pandas as pd
import matplotlib.pyplot as plt
Copy after login
  1. Create and populate your DataFrame: To create a stacked bar chart, it's recommended to use a pandas DataFrame. Here's an example DataFrame with three columns: 'A', 'B', and 'C'.
# sample DataFrame
df = pd.DataFrame({'A': [45, 17, 47], 'B': [91, 70, 72], 'C': [68, 43, 13]})
Copy after login
  1. Plot the stacked bar chart: Utilize the DataFrame to plot the stacked bar chart.
ax = df.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0, xlabel='Class', ylabel='Count')
Copy after login
  1. Label the bars: Now, let's label the bars while ensuring they are centered. Use bar_label to accomplish this.
for c in ax.containers:
    ax.bar_label(c, label_type='center')
Copy after login

Optional Customization

  • Zero or small labels: For segments with zero or small values, adjust the label visibility as needed. For example, display the values only when they exceed a certain threshold or use the label_type='edge' option.
labels = [v.get_height() if v.get_height() > 0 else '' for v in c]  # for segments with small or zero values
Copy after login
  • Custom format: Modify the label format to meet your requirements.
ax.bar_label(c, fmt=lambda x: f'{x:.0f}' if x > 0 else '', label_type='center')  # to show no decimal places
Copy after login

Seaborn Alternative

If you prefer working with seaborn, you can also create a stacked bar chart and label the bars.

  1. Prepare the DataFrame: Similar to matplotlib, create a pandas DataFrame with the data.
  2. Convert DataFrame to long form: seaborn requires the DataFrame to be in a long form, which can be achieved using melt.
  3. Plot the chart and label the bars: Plot the stacked bar chart and apply bar_label as in matplotlib.

The above is the detailed content of How to Center Data Labels in a Matplotlib Stacked Bar Chart?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template