How to create multiple histograms on separate graphs with matplotlib?

Freya Lumb picture Freya Lumb · Aug 21, 2014 · Viewed 22k times · Source

I have 5 data sets from which I want to create 5 separate histograms. At the moment they are all going on one graph. How can I change this so that it produces two separate graphs?

For simplicity, in my example below I am showing just two histograms. I am looking at the distribution of angle a at 3 different times and the same for 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()

Answer

Roger Fan picture Roger Fan · Aug 21, 2014

This is probably when you want to use matplotlib's object-oriented interface. There are a couple ways that you could handle this.

First, you could want each plot on an entirely separate figure. In which case, matplotlib lets you keep track of various figures.

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 divide your figure into multiple subplots and plot a histogram on each of those. In which case matplotlib lets you keep track of the 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')

Answer to this question explain the numbers in add_subplot.