Plot Two Histograms Together in Matplotlib
We could plot two histograms in one figure at the same time. Below shows methods to create the two histograms with and without overlapping bars.
Two Histograms Without Overlapping Bars
Working Example Codes:
import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0, 3, 3000)
b = np.random.normal(2, 4, 2000)
bins = np.linspace(-10, 10, 20)
plt.hist([a, b], bins, label=['a', 'b'])
plt.legend(loc='upper left')
plt.show()
Two Histograms With Overlapping Bars
Working Example Codes:
import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0, 3, 1000)
b = np.random.normal(2, 4, 900)
bins = np.linspace(-10, 10, 50)
plt.hist(a, bins, alpha = 0.5, label='a')
plt.hist(b, bins, alpha = 0.5, label='b')
plt.legend(loc='upper left')
plt.show()
When we call plt.hist
twice to plot the histograms individually, the two histograms will have the overlapped bars as you could see above.
The alpha
property specifies the transparency of the plot. 0.0
is transparent and 1.0
is opaque.
When alpha
is set to be 0.5 for both histograms, the overlapped area shows the combined color. But if alpha
is 0.0
, the default value, overlapped bar only shows the color of the higher value among two histograms and the other color is hidden, as shown below.
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.