简体   繁体   中英

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:

不均匀的直方图

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!

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)

在此输入图像描述

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 (ba)/n the same, you should end up with the same bin sizes.

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)

两个具有相同分级的matplotlib直方图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM