WeirdGeek

Data Science | Machine Learning | Automation

  • Data Analytics
  • Python
  • Data Science
  • Google Apps Script
  • Machine Learning
  • Artificial Intelligence
  • SQL Server

23/11/2018 By WeirdGeek 1 Comment

Plotting stacked histogram using Python’s Matplotlib library

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()

stacked histogram

 

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.

Related posts:

  1. Plotting Stacked Step histogram (unfilled) using Python’s Matplotlib library
  2. Plotting stacked bar graph using Python’s Matplotlib library
  3. Plotting multiple bar graph using Python’s Matplotlib library
  4. Plotting multiple histograms with different length using Python’s Matplotlib library

Filed Under: Data Analytics, Python Tagged With: Matplotlib, Python, Stacked Histogram

Comments

  1. Rogerio says

    03/01/2022 at 4:22 pm

    How can i change the colors?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Subscribe to my Blog !!

Enter your email below to subscribe my blog and get the latest post right in your inbox.

  • Home
  • Terms
  • Privacy
  • Contact Us

Copyright © 2025 · WeirdGeek · All trademarks mentioned are the property of their respective owners.