In my previous posts, we have seen how we can plot multiple bar graph and stacked bar graph. In this post, we will see how we can plot a stacked histogram using Python’s Matplotlib library.

**First** of all, to create any type of histogram whether it’s a simple histogram or a stacked histogram, we need to import libraries that will help us to implement our task.

- From
**the NumPy**library, we will use np.random.randn(1000, 3) which will create a 1000 arrays with 3 random values in each array - And the final and most important library which helps us to visualize our data is
**Matplotlib**.

With the below lines of code, we can import all three libraries with their standard alias.

import numpy as np import matplotlib.pyplot as plt

##### Plotting stacked histogram using Python’s Matplotlib library:

The below code will create the stacked histogram using Python’s Matplotlib library. To plot, we have to pass the parameter** stacked = True** in the plt.hist () which informs Matplotlib library to perform the stacking task. Have a look at the below code:

n_bins=30 x = np.random.randn(1000, 3) colors = ['blue', 'orange', 'green'] plt.hist(x, n_bins, density=1, histtype='bar', stacked=True, label=colors) plt.legend(loc="upper right") plt.title('Stacked-histogram ') plt.show()

Hope you like our post – Plotting stacked histogram using Python’s Matplotlib library. To learn more about Matplotlib package, you can go through the official documentation here.

## Leave a Reply