Create a stacked bar plot in Matplotlib

Python

Matplotlib

Bar

Create stacked

Luc B.

Python

Matplotlib

Bar Plot

Stacked bar plots allows visualizers to show their data's compositional parts while still comparing total values. This is accomplised by using multiple colors in each bar to show the size of different subgroups.

A visualization with similar applications is the grouped bar plot.

Code Example

To create a stacked bar chart, use the bottom parameter to plt.bar().

import matplotlib.pyplot as plt

bottom = [60, 56, 63, 75, 48]
top = [38, 52, 40, 80, 55]
labels = ["This", "is", "a", "bar", "plot"]

# Create stacked bar plot here
plt.bar(labels, bottom)
plt.bar(labels, top, bottom=bottom)

plt.legend(["Bottom Group", "Top Group"])
plt.show()

png

The bottom parameter causes each bar to be offset vertically by a constant. Coupling a vertically offset bar chart with a a bar chart aligned with 0 creates the stacked bar chart we desire.