Question

I've spent some time searching the interwebs for an answer for this, and I have tried looking all over SO for an answer too, but I think I do not have the correct terminology down... Please excuse me if this is a duplicate of some known problem, I'd happily delete my post and refer to that post instead!

In any case, I am trying to plot two histograms on the same figure in Matplotlib. My two data sources are lists of 500 elements long. To provide an illustration of the problem I am facing, please see the following image:

Uneven histograms

As you can see, the histogram has uneven bin sizes under default parameters, even though the number of bins is the same. I would like to guarantee that the bin widths for both histograms are the same. Is there any way I can do this?

Thanks in advance!

Was it helpful?

Solution

I think a consistent way that will easily work for most cases, without having to worry about what is the distribution range for each of your datasets, will be to put the datasets together into a big one, determine the bins edges and then plot:

a=np.random.random(100)*0.5 #a uniform distribution
b=1-np.random.normal(size=100)*0.1 #a normal distribution 
bins=np.histogram(np.hstack((a,b)), bins=40)[1] #get the bin edges
plt.hist(a, bins)
plt.hist(b, bins)

enter image description here

OTHER TIPS

You should use bins from the values returned by hist:

import numpy as np
import matplotlib.pyplot as plt

foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution

_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)

Two matplotlib histograms with same binning

I guess you can use the range parameter together with the bin parameter to come up with the same bin size for both data sets.

plt.hist(x, bins=n, range=(a,b))

where if you keep the ratio of (b-a)/n the same, you should end up with the same bin sizes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top