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:
-
Import necessary modules: Begin by importing the essential libraries.
import pandas as pd
import matplotlib.pyplot as plt
Copy after login
-
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
-
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
-
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.
-
Prepare the DataFrame: Similar to matplotlib, create a pandas DataFrame with the data.
-
Convert DataFrame to long form: seaborn requires the DataFrame to be in a long form, which can be achieved using melt.
-
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!