在一个直方图上绘制两组数据

时间:2017-03-21 14:50:52

标签: matlab octave probability probability-density bernoulli-probability

我刚刚开始使用Octave并试图模拟二项式随机变量的10,000个结果,定义如下:

X~Bi(5,0.2)

我用以下函数绘制了结果:

function x = generate_binomial_bernoulli(n,p,m)
  % generate Bi(n, p) outcomes m times

  x = zeros(1,m);       % allocate array for m simulations
  for i = 1:m           % iterate over m simulations
    successes = 0;      % count the number of successful trials per simualtion (0-5)
    for j = 1:n         % iterate through the n trials
      u = rand;         % generate random nuumber from 0-1
      if (u <= p)       % if random number is <= p
        successes++;    % count it as a success
      endif
    end
    x(i) = successes;   % store the number of successful trials in this simulation
  end

  alphabet_x=[0:n];     % create an array from 0 to n        
  hist(x,alphabet_x);   % plot graph     

end

然后我用generate_binomial_bernoulli(5, 0.2, 10000)调用该函数。

这是模拟5个伯努利试验,每个试验的成功概率为0.2,重复5次试验10,000次,并绘制成功次数的分布图。该图显示了模拟的实验结果。

enter image description here

我现在也被要求绘制理论结果,我最好的猜测是在x轴上成功分布的正态分布图(0.2 * 5 = 1)。

  1. 我如何创建此图,并将其显示在相同的直方图上?
  2. 我怎样才能显示我的图形,其中x轴横跨0到5,标记两个轴,两个直方图用图例颜色编码?
  3. 修改

    这是我目前的功能,我试图绘制标准化/理论曲线:

    function x = generate_binomial_bernoulli(n,p,m)
      % generate Bi(n, p) outcomes m times
    
      emperical = zeros(1,m);             % allocate array for m simulations
      for i = 1:m                         % iterate over m simulations
        successes = 0;                    % count the number of successful trials per simualtion (0-5)
        for j = 1:n                       % iterate through the n trials
          u = rand;                       % generate random nuumber from 0-1
          if (u <= p)                     % if random number is <= p
            successes++;                  % count it as a success
          endif
        end
        emperical(i) = successes;         % store the number of successful trials in this simulation
      end
    
      close all;                          % close any existing graphs
    
      x_values = [0:n];                   % array of x-axis values        
      hist(emperical, x_values, "facecolor", "r"); % plot empirical data
      xlim([-0.5 (n + 0.5)]);             % set x-axis to allow for histogram bar widths
    
      hold on;                            % hold current graph
    
      mean = n * p;                       % theoretical mean
      norm = normpdf(x_values, mean, 1);  % normalised y values
      plot(x_values, norm, "color", "b"); % plot theoretical distribution
    
      legend('Emprical', 'Theoretical');   
    
    end
    

    如下图所示,此曲线仅沿y轴延伸到非常低的高度,但我不知道如何在整个数据集中跨越它。

    enter image description here

1 个答案:

答案 0 :(得分:0)

获取直方图编号和分档:

[counts,centers] = hist(x);

规范化:

freq = counts/sum(counts);

绘制标准化直方图:

bar(centers,freq)
相关问题