Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot a Bar Chart with multiple labels in Matplotlib?
To plot a bar chart with multiple labels in Matplotlib, we can create grouped bars with data labels. This technique is useful for comparing values across different categories and groups.
Basic Grouped Bar Chart
First, let's create the data and set up the basic grouped bar chart ?
import matplotlib.pyplot as plt
import numpy as np
# Sample data for comparison
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
# Set up the positions and width
ind = np.arange(len(men_means)) # x locations for groups
width = 0.35 # width of bars
# Create figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Create grouped bars
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men', alpha=0.8)
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women', alpha=0.8)
print("Basic grouped bar chart created successfully")
Basic grouped bar chart created successfully
Adding Labels and Formatting
Now let's add proper labels, titles, and formatting to make the chart more informative ?
import matplotlib.pyplot as plt
import numpy as np
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men', alpha=0.8)
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women', alpha=0.8)
# Add labels and formatting
ax.set_ylabel('Scores')
ax.set_title('Scores by Group and Gender')
ax.set_xticks(ind)
ax.set_xticklabels(('Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'))
ax.legend()
plt.tight_layout()
plt.show()
Adding Data Labels on Bars
To add value labels on top of each bar, we'll create a function to automatically label all bars ?
import matplotlib.pyplot as plt
import numpy as np
def autolabel(ax, rects, xpos='center'):
"""Add value labels on bars"""
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # 3 points offset
textcoords="offset points",
ha=ha[xpos], va='bottom')
# Data
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
# Create bars
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
label='Men', alpha=0.8, color='skyblue')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
label='Women', alpha=0.8, color='lightcoral')
# Formatting
ax.set_ylabel('Scores')
ax.set_title('Scores by Group and Gender with Data Labels')
ax.set_xticks(ind)
ax.set_xticklabels(('Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'))
ax.legend()
# Add labels to bars
autolabel(ax, rects1, "left")
autolabel(ax, rects2, "right")
plt.tight_layout()
plt.show()
Customizing Label Positions
You can customize label positions and styles for better readability ?
import matplotlib.pyplot as plt
import numpy as np
def custom_autolabel(ax, rects, labels, offset_y=3):
"""Add custom labels with specific positioning"""
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.annotate(label,
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, offset_y),
textcoords="offset points",
ha='center', va='bottom',
fontweight='bold', fontsize=10)
# Sample data with custom labels
categories = ['Q1', 'Q2', 'Q3', 'Q4']
values_2022 = [45, 52, 48, 61]
values_2023 = [50, 58, 44, 67]
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x - width/2, values_2022, width, label='2022',
color='#FF9999', alpha=0.8)
bars2 = ax.bar(x + width/2, values_2023, width, label='2023',
color='#66B2FF', alpha=0.8)
# Add custom labels
custom_autolabel(ax, bars1, [f'{v}%' for v in values_2022])
custom_autolabel(ax, bars2, [f'{v}%' for v in values_2023])
ax.set_xlabel('Quarter')
ax.set_ylabel('Performance (%)')
ax.set_title('Quarterly Performance Comparison')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
ax.set_ylim(0, max(max(values_2022), max(values_2023)) + 10)
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
width |
Bar width (0.35 is common for grouped bars) | width = 0.35 |
alpha |
Transparency (0-1) | alpha = 0.8 |
yerr |
Error bars data | yerr = std_values |
xytext |
Label offset position | xytext = (0, 3) |
Conclusion
Use the autolabel() function to add value labels on grouped bar charts. Adjust width and positioning parameters to create clear, readable visualizations with multiple data series and labels.
