How can I create multiple histograms on separate plots using matplotlib?
I have 5 datasets from which I want to create 5 separate histograms. At the moment, they all follow the same schedule. How can I change this so that it creates two separate plots?
For simplicity, in my example below, I only show two histograms. I am considering the angle distribution a
3 times and the same for the angle b
.
n, bins, patches = plt.hist(a)
plt.xlabel('Angle a (degrees)')
plt.ylabel('Frequency')
n, bins, patches = plt.hist(b)
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)
plt.xlabel('Angle b(degrees)')
plt.title('Histogram of b')
plt.ylabel('Frequency')
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)
plt.show()
source to share
This is probably when you want to use matplotlib's object oriented interface . There are several ways you could handle this.
First, you may want each plot to be a completely separate figure. In this case matplotlib allows you to keep track of different numbers.
import numpy as np import matplotlib.pyplot as plt a = np.random.normal(size=200) b = np.random.normal(size=200) fig1 = plt.figure() ax1 = fig1.add_subplot(1, 1, 1) n, bins, patches = ax1.hist(a) ax1.set_xlabel('Angle a (degrees)') ax1.set_ylabel('Frequency') fig2 = plt.figure() ax2 = fig2.add_subplot(1, 1, 1) n, bins, patches = ax2.hist(b) ax2.set_xlabel('Angle b (degrees)') ax2.set_ylabel('Frequency')
Or you can split your shape into multiple subplots and plot a bar chart on each one. In this case matplotlib allows you to keep track of various subplots.
fig = plt.figure() ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) n, bins, patches = ax1.hist(a) ax1.set_xlabel('Angle a (degrees)') ax1.set_ylabel('Frequency') n, bins, patches = ax2.hist(b) ax2.set_xlabel('Angle b (degrees)') ax2.set_ylabel('Frequency')
The answer to this question explains the numbers in add_subplot
.
source to share