Overlay multiple histograms in a Matplotlib plot

Python

Matplotlib

Histogram

Create overlayed

Luc B.

Python

Matplotlib

Histogram

Histograms show the number of occurrences of each value of a variable, visualizing the distribution of results. If results span multiple groups, there are several techniques for expressing the histogram's group composition including the stacked histogram and grouped histogram. While both these methods work, it is often clearer to just create individual histograms for each group and use transparency to make them visible.

Code Example

To overlay histograms, make multiple calls to plt.hist() and use the alpha parameter to make the distributions transparent.

import matplotlib.pyplot as plt
import numpy as np

# Generate two normal distributions around different means
group1 = np.random.normal(0, size=1000)
group2 = np.random.normal(2, size=1000)

# Create two overlayed histograms
plt.hist(group1, alpha=0.6)
plt.hist(group2, alpha=0.6)

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

png