Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: How to make two histograms have the same bin width?

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!

like image 276
ericmjl Avatar asked May 12 '14 19:05

ericmjl


People also ask

Can histograms have different bin widths?

Most histograms use bin widths that are as equal as possible, but it is also possible to use unequal bin widths (see the 'Variable bin widths' section of Histogram). A recommended strategy is to size bins so the number of values they contain is approximately equal.

Can we draw two histograms together?

For plotting two histograms together, we have to use hist() function separately with two datasets by giving some setting. Used to represent the label of the histogram it is of string type. Used for setting amount of transparency. Used to represent the name or label of the histogram.


1 Answers

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

like image 113
CT Zhu Avatar answered Sep 20 '22 03:09

CT Zhu