0

我正在通过 Matlab 在 1 个图中绘制 2 个分布的 2 个直方图。然而,结果显示 2 个直方图没有相同的 bin 宽度,尽管我对 bin 使用了相同的数字。我们如何使 2 个直方图具有相同的 bin 宽度?

我的代码很简单,如下所示:

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;
4

3 回答 3

1

这可以通过简单地使用从一个调用到 hist 的 bin 中心作为另一个调用的 bin 来完成

例如

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

注意all(aBins==bBins)= 1


但是,当两个数据集的最小值和最大值不相似时,此方法会丢失信息*,一种简单的解决方案是根据组合数据创建 bin

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

*如果范围差异很大,最好手动创建 bin 中心向量


(重新阅读问题后)如果您想要控制箱宽度,则最好不要使用相同的箱来手动创建箱中心......

为此,创建一个 bin 中心向量以传递给 hist,

例如 - 请注意,此处仅对一组数据强制执行箱数

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

然后使用

aCounts = hist( a , aBins );
bCounts = hist( b , bBins );
于 2014-09-18T15:02:45.723 回答
1

使用带有 'BinWidth' 选项的 histcounts

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

IE

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


bar(hist1)
bar(hist2)
于 2016-09-27T14:14:07.307 回答
0

hist当第二个参数是向量而不是标量时,的行为会有所不同。

如文档中所示,不要指定多个 bin,而是使用向量指定 bin 限制(请参阅“指定 bin 间隔”):

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;

这导致:

如果您仔细观察,仍然可以看到蓝色条形顶部

于 2014-09-18T14:53:12.347 回答