0
0
Matplotlibdata~7 mins

Grouped bar charts in Matplotlib

Choose your learning style9 modes available
Introduction

Grouped bar charts help compare different groups side by side. They make it easy to see differences between categories and groups.

Comparing sales of different products across several months.
Showing test scores of students in different subjects by class.
Visualizing survey results for multiple questions across age groups.
Comparing revenue from different stores over several years.
Syntax
Matplotlib
import matplotlib.pyplot as plt

labels = ['Group1', 'Group2', 'Group3']
values1 = [10, 20, 30]
values2 = [15, 25, 35]

x = range(len(labels))
width = 0.35

plt.bar([p - width/2 for p in x], values1, width=width, label='Set 1')
plt.bar([p + width/2 for p in x], values2, width=width, label='Set 2')

plt.xticks(x, labels)
plt.legend()
plt.show()
Use the width variable to control bar thickness and spacing.
Shift bar positions left and right by half the width to group bars side by side.
Examples
Two groups of bars shown side by side for categories A, B, and C.
Matplotlib
labels = ['A', 'B', 'C']
values1 = [5, 7, 9]
values2 = [6, 8, 10]

x = range(len(labels))
width = 0.4

plt.bar([p - width/2 for p in x], values1, width=width, label='First')
plt.bar([p + width/2 for p in x], values2, width=width, label='Second')

plt.xticks(x, labels)
plt.legend()
plt.show()
Three groups of bars for each category, spaced evenly.
Matplotlib
labels = ['X', 'Y']
values1 = [3, 6]
values2 = [4, 5]
values3 = [2, 7]

x = range(len(labels))
width = 0.25

plt.bar([p - width for p in x], values1, width=width, label='Set 1')
plt.bar(x, values2, width=width, label='Set 2')
plt.bar([p + width for p in x], values3, width=width, label='Set 3')

plt.xticks(x, labels)
plt.legend()
plt.show()
Sample Program

This program creates a grouped bar chart comparing fruit sales in 2023 and 2024 side by side.

Matplotlib
import matplotlib.pyplot as plt

# Categories
labels = ['Apples', 'Bananas', 'Cherries']

# Data for two groups
sales_2023 = [30, 45, 10]
sales_2024 = [40, 35, 15]

x = range(len(labels))
width = 0.35

# Plot bars for 2023 shifted left
plt.bar([p - width/2 for p in x], sales_2023, width=width, label='2023')

# Plot bars for 2024 shifted right
plt.bar([p + width/2 for p in x], sales_2024, width=width, label='2024')

# Label x-axis with category names
plt.xticks(x, labels)

# Add title and legend
plt.title('Fruit Sales Comparison')
plt.legend()

# Show the plot
plt.show()
OutputSuccess
Important Notes

Make sure the width times number of groups fits well to avoid bars overlapping.

Use plt.xticks() to label the groups clearly.

Adding a legend helps identify each group easily.

Summary

Grouped bar charts show multiple sets of data side by side for easy comparison.

Shift bars left and right by half the bar width to group them.

Label axes and add legends for clarity.