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
Create a grouped bar plot in Matplotlib
Matplotlib is a powerful data visualization library in Python that enables you to create various types of charts and plots. A grouped bar plot is particularly useful for comparing multiple categories across different groups, allowing you to visualize relationships between categorical variables side by side.
What is a Grouped Bar Plot?
A grouped bar plot displays multiple bars for each category, grouped together to compare different data series. Each group represents a category, and within each group, individual bars represent different data series or variables.
Basic Grouped Bar Plot
Here's how to create a simple grouped bar plot using sample sales data ?
import numpy as np
import matplotlib.pyplot as plt
# Sample data: quarterly sales for different products
products = ['Product A', 'Product B', 'Product C', 'Product D']
q1_sales = [20, 35, 30, 25]
q2_sales = [25, 30, 35, 30]
q3_sales = [30, 25, 20, 35]
# Set position and width of bars
x_pos = np.arange(len(products))
bar_width = 0.25
# Create the grouped bars
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x_pos - bar_width, q1_sales, bar_width, label='Q1', color='skyblue')
bars2 = ax.bar(x_pos, q2_sales, bar_width, label='Q2', color='orange')
bars3 = ax.bar(x_pos + bar_width, q3_sales, bar_width, label='Q3', color='lightgreen')
# Add labels and title
ax.set_xlabel('Products')
ax.set_ylabel('Sales (in thousands)')
ax.set_title('Quarterly Sales Comparison by Product')
ax.set_xticks(x_pos)
ax.set_xticklabels(products)
ax.legend()
# Add value labels on bars
for bars in [bars1, bars2, bars3]:
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height + 0.5,
f'{height}', ha='center', va='bottom')
plt.tight_layout()
plt.show()
Using a Dictionary for Data Organization
For better data organization, you can use a dictionary to store multiple data series ?
import numpy as np
import matplotlib.pyplot as plt
# Data organized in dictionary format
data = {
'Team A': [85, 90, 88, 92],
'Team B': [78, 85, 90, 87],
'Team C': [92, 88, 85, 90]
}
categories = ['Math', 'Science', 'English', 'History']
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1']
# Calculate positions
x_pos = np.arange(len(categories))
bar_width = 0.25
num_groups = len(data)
fig, ax = plt.subplots(figsize=(12, 6))
# Create bars for each team
for i, (team, scores) in enumerate(data.items()):
offset = (i - (num_groups - 1) / 2) * bar_width
ax.bar(x_pos + offset, scores, bar_width,
label=team, color=colors[i], alpha=0.8)
# Customize the plot
ax.set_xlabel('Subjects')
ax.set_ylabel('Average Scores')
ax.set_title('Team Performance Comparison Across Subjects')
ax.set_xticks(x_pos)
ax.set_xticklabels(categories)
ax.legend()
ax.grid(True, alpha=0.3)
# Set y-axis range for better visualization
ax.set_ylim(70, 95)
plt.tight_layout()
plt.show()
Horizontal Grouped Bar Plot
You can also create horizontal grouped bar plots using barh() ?
import numpy as np
import matplotlib.pyplot as plt
# Department performance data
departments = ['Sales', 'Marketing', 'Engineering', 'HR']
current_year = [85, 78, 92, 88]
previous_year = [80, 82, 87, 85]
y_pos = np.arange(len(departments))
bar_height = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
# Create horizontal bars
bars1 = ax.barh(y_pos - bar_height/2, current_year, bar_height,
label='Current Year', color='steelblue')
bars2 = ax.barh(y_pos + bar_height/2, previous_year, bar_height,
label='Previous Year', color='lightcoral')
# Customize the plot
ax.set_ylabel('Departments')
ax.set_xlabel('Performance Score')
ax.set_title('Department Performance: Year-over-Year Comparison')
ax.set_yticks(y_pos)
ax.set_yticklabels(departments)
ax.legend()
# Add value labels
for bars in [bars1, bars2]:
for bar in bars:
width = bar.get_width()
ax.text(width + 1, bar.get_y() + bar.get_height()/2,
f'{width}', ha='left', va='center')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
width |
Width of individual bars | 0.25 |
label |
Label for legend | 'Series 1' |
color |
Bar color | 'skyblue' |
alpha |
Transparency (0-1) | 0.8 |
Best Practices
Use consistent bar widths Keep the same width for all bars in a group
Choose distinct colors Use colors that are easily distinguishable
Add legends Always include a legend to identify different data series
Label your axes Provide clear labels for both x and y axes
Consider spacing Adjust spacing between groups for better readability
Conclusion
Grouped bar plots are excellent for comparing multiple data series across categories. Use appropriate spacing, colors, and labels to create clear, informative visualizations that effectively communicate your data insights.
