Create a grouped bar plot in Matplotlib

Python

Matplotlib

Bar

Create grouped

Luc B.

Python

Matplotlib

Bar Plot

Grouped bar plots use multiple bars for each x-value to compare results from different groups. For example, we could compare the calories injested by kids versus adults for each hour of the day. Or, we could compare the average GPA's of kids who do and don't participate in extracurriculars across different grade levels.

A visualization with similar applications is the stacked bar plot.

Code Example

To create a grouped bar chart, use the plt.bar() function and leverage the x-position and width of the bars to create groups.

import matplotlib.pyplot as plt

data_group1 = [60, 56, 63, 75, 48]
data_group2 = [38, 52, 40, 80, 55]
x_vals = range(len(data_group1))

# Create grouped bar plot here
plt.bar([x-0.14 for x in x_vals], data_group1, width=0.25)
plt.bar([x+0.14 for x in x_vals], data_group2, width=0.25)

plt.legend(["Group 1", "Group 2"], loc="upper left")
plt.show()

png

By offsetting the x positions of the bars and adjusting the bar width, we're able to group the bars around a specific x-value. To add another group, include another call to plt.bar(). To make the bars horizontal instead of vertical, use plt.barh().

More Examples

Use Non-Numerical Tick Labels

Since grouped bar plots require the use of numerical x-values, we have to separately set the tick labels using the tick_label parameter to plt.bar().

import matplotlib.pyplot as plt

data_group1 = [60, 56, 63, 75, 48]
data_group2 = [38, 52, 40, 80, 55]
x_vals = range(len(data_group1))

# Use non-numerical tick labels
plt.bar([x-0.14 for x in x_vals], data_group1, width=0.25)
plt.bar([x+0.14 for x in x_vals], data_group2, width=0.25,
        tick_label=["This", "is", "a", "bar", "plot"])

plt.legend(["Group 1", "Group 2"], loc="upper left")
plt.show()

png