Create a stacked histogram in Matplotlib

Python

Matplotlib

Histogram

Create stacked

Luc B.

Python

Matplotlib

Histogram

Histograms are powerful visualizations that show the number of occurrences of each value of a variable, creating a distribution of results. Stacked histograms organize occurrences into groups with an associated color, and each bar consists of multiple colors, representing contributions from different groups. This makes the visualization more expressive.

A visualization with similar applications is the grouped histogram.

Code Example

To create a stacked histogram, organize your data into separate arrays according to their group, and use the stacked parameter to plt.hist().

import matplotlib.pyplot as plt

group1 = [1, 1, 1, 2, 2, 3, 4]
group2 = [2, 2, 2, 1, 1, 3, 1]
group3 = [3, 3, 3, 2, 2, 1, 2]

# Create a stacked histogram here
plt.hist([group1, group2, group3], stacked=True,
         bins=[1, 2, 3, 4, 5], rwidth=0.9, align="left")

plt.legend(["Group 1", "Group 2", "Group 3"])
plt.xticks([1, 2, 3, 4])
plt.ylabel("Quantity")
plt.xlabel("Value")
plt.show()

png