【问题标题】:MATLAB: How to make 2 histograms have the same bin width?MATLAB:如何使 2 个直方图具有相同的 bin 宽度?
【发布时间】:2014-09-18 14:34:44
【问题描述】:

我正在通过 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;

【问题讨论】:

    标签: matlab histogram bins


    【解决方案1】:

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

    例如

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

    注意all(aBins==bBins) = 1


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

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

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


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

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

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

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

    【讨论】:

    • 我试过你的方法,虽然两者的bin宽度相同,但第二个直方图被截断了......
    • 需要考虑到这一点,最好基于两种分布组合创建 bin...即将编辑
    • 谢谢你的方法,我的问题完全解决了
    【解决方案2】:

    使用带有“BinWidth”选项的历史计数

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

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

    【讨论】:

      【解决方案3】:

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

      不要指定 bin 数量,而是使用向量指定 bin 限制,如 documentation 中所示(请参阅“指定 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;
      

      这会导致:

      【讨论】:

      • 我尝试了向量而不是标量。但是,在我的情况下,第一个直方图范围为 [-50,50],第二个直方图范围为 [-2,2]。如果我使用的范围是 [-50,50] 或 [-2,2],则在同一图中绘制时其中一个会消失:(
      • 感谢您的解决方案。但是,就我而言,RTL 的方法比您的方法更有效。