How to create multiple histograms on separate graphs with matplotlib?
Asked Answered
M

2

8

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()
Magic answered 21/8, 2014 at 15:40 Comment(0)
U
14

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.

Uranyl answered 21/8, 2014 at 16:2 Comment(0)
H
8

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.

Hora answered 26/8, 2014 at 13:32 Comment(1)
This is how I used it too, but that's also why I am here. Since when you start using data.a.hist() and data.b.hist() they all go into one single chart, while I want them to be in separate charts. So the accepted answer indeed helps here while this one unfortunately not :)Baskin

© 2022 - 2024 — McMap. All rights reserved.