0
0
Matplotlibdata~5 mins

Multiple histograms overlay in Matplotlib

Choose your learning style9 modes available
Introduction

Overlaying multiple histograms helps compare different data groups visually in one chart.

Comparing test scores of two classes in one graph.
Showing sales distribution for different months together.
Visualizing heights of men and women in the same plot.
Comparing customer ages from two regions side by side.
Syntax
Matplotlib
import matplotlib.pyplot as plt

plt.hist(data1, bins=number, alpha=transparency, label='label1')
plt.hist(data2, bins=number, alpha=transparency, label='label2')
plt.legend()
plt.show()

alpha controls transparency so histograms can be seen overlapping.

Use label and plt.legend() to add a legend for clarity.

Examples
Plot two histograms together using a list of datasets.
Matplotlib
plt.hist([data1, data2], bins=10, alpha=0.5, label=['Group 1', 'Group 2'])
plt.legend()
plt.show()
Plot two histograms separately with same bins and transparency.
Matplotlib
plt.hist(data1, bins=15, alpha=0.7, label='Set A')
plt.hist(data2, bins=15, alpha=0.7, label='Set B')
plt.legend()
plt.show()
Sample Program

This code creates two groups of random numbers with different averages and spreads. It then plots their histograms on the same chart with some transparency so you can see where they overlap.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create two sets of random data
np.random.seed(0)
data1 = np.random.normal(50, 10, 1000)  # Group 1
np.random.seed(1)
data2 = np.random.normal(60, 15, 1000)  # Group 2

# Plot histograms overlay
plt.hist(data1, bins=30, alpha=0.5, label='Group 1')
plt.hist(data2, bins=30, alpha=0.5, label='Group 2')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Overlay of Two Histograms')
plt.legend()
plt.show()
OutputSuccess
Important Notes

Make sure bins are the same for all histograms to compare properly.

Adjust alpha to see overlapping areas clearly.

Use plt.legend() to identify each histogram easily.

Summary

Overlaying histograms helps compare multiple data groups visually.

Use alpha for transparency and label with legend for clarity.

Keep bins consistent for meaningful comparison.