Stacked histogram is widely used in papers. In this tutorial, we will introduce how to create a stacked histogram using matplotlib in python.
Stacked histogram likes:
To create a stacked histogram above, you can refer to this example:
Create X, Y1 and Y2
import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn') X = np.arange(5) + 1 Y1 = np.array([0.5, 0.27, 0.51, 0.56, 0.8]) Y2 = np.random.random(5) print(Y2)
Here we use numpy to create 5 randomized float numbers.
[0.17119526 0.20921575 0.8304114 0.53602932 0.8907226 ]
Show stacked histogram
We can use code below to display a stacked histogram.
ax = plt.subplot() ax.bar(X, Y1, tick_label=['I', 'II', 'III', 'IV', 'V'], label='Y1') ax.bar(X, Y2, bottom=Y1, label='Y2') plt.legend() plt.show()
We should notice code: bottom=Y1, which means Y1 is at the bottom of Y2. We also can make Y1 be at the top of Y2.
ax.bar(X, Y1, bottom=Y2, tick_label=['I', 'II', 'III', 'IV', 'V'], label='Y1') ax.bar(X, Y2, label='Y2') plt.legend() plt.show()
Run this code, you will get a stacked histogram below.