Normalizing a histogram and having the y-axis in percentages in matlab

前端 未结 1 839
借酒劲吻你
借酒劲吻你 2020-12-09 22:14

Edit: Alright, so I answered my own question, by reading older questions a bit more. I apologize for asking the question! Using the code

Y = rand(10,1);
C =         


        
相关标签:
1条回答
  • 2020-12-09 22:45

    (Just to close the question)

    Histogram is an absolute frequency plot so the sum of all bin frequencies (sum of the output vector of hist function) is always the number of elements in its input vector. So if you want a percentage output all you need to do is dividing each element in the output by that total number:

    x = randn(10000, 1);
    numOfBins = 100;
    [histFreq, histXout] = hist(x, numOfBins);
    figure;
    bar(histXout, histFreq/sum(histFreq)*100);
    xlabel('x');
    ylabel('Frequency (percent)');
    

    enter image description here

    If you want to reconstruct the probability density function of your data, you need to take into account the bin size of the histogram and divide the frequencies by that:

    x = randn(10000, 1);
    numOfBins = 100;
    [histFreq, histXout] = hist(x, numOfBins);
    binWidth = histXout(2)-histXout(1);
    figure;
    bar(histXout, histFreq/binWidth/sum(histFreq));       
    xlabel('x');
    ylabel('PDF: f(x)');
    hold on
    % fit a normal dist to check the pdf
    PD = fitdist(x, 'normal');
    plot(histXout, pdf(PD, histXout), 'r');
    

    enter image description here


    Update:

    Since MATLAB R2014b, you can use the 'histogram' command to easily produce histograms with various normalizations. For example, the above becomes:

    x = randn(10000, 1);
    figure;
    h = histogram(x, 'normalization', 'pdf');
    xlabel('x');
    ylabel('PDF: f(x)');
    hold on
    % fit a normal dist to check the pdf
    PD = fitdist(x, 'normal');
    plot(h.BinEdges, pdf(PD, h.BinEdges), 'r');
    

    enter image description here

    0 讨论(0)
提交回复
热议问题