Freya Lumb
Freya Lumb

Reputation: 81

How to create multiple histograms on separate graphs with matplotlib?

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

Upvotes: 8

Views: 37438

Answers (2)

matt_s
matt_s

Reputation: 1075

I recently used pandas for doing the same thing. If you're reading from csv/text then it could be really easy.

import pandas as pd
data = pd.read_csv("yourfile.csv") # columns a,b,c,etc
data.hist(bins=20)

It's really just wrapping the matplotlib into one call, but works nicely.

Upvotes: 8

Roger Fan
Roger Fan

Reputation: 5045

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.

Upvotes: 14

Related Questions