Steven Huynh
Steven Huynh

Reputation: 23

MATLAB: How to make 2 histograms have the same bin width?

I am plotting 2 histograms of 2 distributions in 1 figure by Matlab. However, the result shows that 2 histograms do not have the same bin width although I use the same number for bins. How can we make 2 histograms have the same bin width?

My code is simple like this:

a = distribution one
b = distribution two
nbins = number of bins
[c,d] = hist(a,nbins);
[e,f] = hist(b,nbins);
%Plotting
bar(d,c);hold on;
bar(f,e);hold off;

Upvotes: 0

Views: 5551

Answers (3)

Gulzar
Gulzar

Reputation: 27956

use histcounts with 'BinWidth' option

https://www.mathworks.com/help/matlab/ref/histcounts.html

i.e

data1 = randn(1000,1)*10;
data2 = randn(1000,1);
[hist1,~] = histcounts(data1, 'BinWidth', 10);
[hist2,~] = histcounts(data2, 'BinWidth', 10);


bar(hist1)
bar(hist2)

Upvotes: 1

RTL
RTL

Reputation: 3587

This can be done by simply using the bins centres from one call to hist as the bins for the another

for example

[aCounts,aBins] = hist(a,nBins);
[bCounts,bBins] = hist(b,aBins);

note that all(aBins==bBins) = 1


This method however will loose information when the min and max values of the two data sets are not similar*, one simple solution is to create bins based on the combined data

[~ , bins] = hist( [a(:),b(:)] ,nBins);
aCounts = hist( a , bins );
bCounts = hist( b , bins );

*if the ranges are vastly different it may be better to create the vector of bin centres manually


(after re-reading the question) If the bin widths are what you want to control not using the same bins creating the bin centers manually is probably best...

to do this create a vector of bin centres to pass to hist,

for example - note the number of bins is only enforced for one set of data here

aBins = linspace( min(a(:)) ,max(a(:) , nBins);
binWidth = aBins(2)-aBins(1);
bBins = min(a):binWidth:max(b)+binWidth/2

and then use

aCounts = hist( a , aBins );
bCounts = hist( b , bBins );

Upvotes: 1

Dev-iL
Dev-iL

Reputation: 24169

The behavior of hist is different when the 2nd argument is a vector instead of a scalar.

Instead of specifying a number of bins, specify the bin limits using a vector, as demonstrated in the documentation (see "Specify Bin Intervals"):

rng(0,'twister')
data1 = randn(1000,1)*10;
rng(1,'twister')
data2 = randn(1000,1);

figure
xvalues1 = -40:40;
[c,d] = hist(data1,xvalues1);
[e,f] = hist(data2,xvalues1);

%Plotting
bar(d,c,'b');hold on;
bar(f,e,'r');hold off;

This results in:

If you look closely, the blue bar tops are still visible "behind" the red

Upvotes: 0

Related Questions