Plot two or more histograms side by side in Python
Hello friends, you know how to plot a histogram in Python. In this tutorial, I will tell you how to plot two or more histograms side by side using matplotlib in Python.
Plot two or more histograms side by side
I have imported the following dependencies in my code to enable me to plot a line.
import matplotlib.pyplot as plt import numpy as np
In order to plot two or more histograms side by side, I have used the subplot()
function. This function helps me plot histograms onto an imaginary grid. You can decide the grid divisions. In my example, I have tried plotting two histograms side by side. I have divided my grid into two parts, grid consists of 1 row and 2 columns. In line 3, I have passed three values as arguments to the subplot function. 1 signifies the no of rows, 2 states the no of columns and 1 in the 3rd position states where in the grid I want to plot my first histogram, at first or at the end. Similarly, before plotting the second histogram, I used the same function with the row and column but I changed the value of the 3rd attribute.
Code :
plot_1 = np.random.rand(20)*9.0 plot_2 = np.random.rand(50)*4.5 plt.subplot(1, 2, 1) plt.hist(plot_1, color = 'orange', edgecolor = 'grey') plt.subplot(1, 2, 2) plt.hist(plot_2, color = 'cyan', edgecolor = 'grey')
Output :
If I do not change the value, it will overlap the first histogram.
Output :
You can also use the subplots()
function to define the position of the plot, as well as index their position and form a grid of specified rows and columns. In the example, I have specified the number of rows as 1 and the number of columns as 3.
Code :
plot_1 = np.random.rand(20)*9.0 plot_2 = np.random.rand(50)*4.5 plot_3 = np.random.rand(25)*5.0 fig, axis = plt.subplots(1, 3) axis[0].hist(plot_1, color = 'orange', edgecolor = 'grey') axis[1].hist(plot_2, color = 'cyan', edgecolor = 'grey') axis[2].hist(plot_3, color = 'green', edgecolor = 'grey')
Output :
You can create a grid with any no of rows and columns using this function. You can also plot histograms and display them in a matrix. However, for the matrix, necessary indexing should be used.
Now you can successfully, plot two or more histograms side by side in Python.
Leave a Reply