Search code examples
matlabhistogramnormalization

How to turn y axis of histogram to show percentage ranging from 0 to 1


I want to change the y axis of the histogram to show percentages ranging from 0 to 1. this is what I've tried, but it doesn't seem to be working.

    myTolerance=1e-12; % in erg units.
      nbins=50;
    for j=1:ntM/100:ntM

       H = histfit(Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV, nbins);
    %Select from column j all rows in column j whose absolute values are 
    %greater than the tolerance.
    H(1).delete; %%Remove bins, only keep the fit.
       set(gca, 'YScale', 'log');
        set(gca, 'XScale', 'log'); % Make logarithmic X
         yt = get(gca, 'YTick');
        set(gca, 'YTick', yt, 'YTickLabel', 
        yt/numel(Wkinet(abs(Wkinet(:,j))>myTolerance)))

      pause;
   end

This is what is currently looks like:

Output Graph

This is what I want:

Desired output graph


Solution

  • Just to simplify the discussion below, the line

    H = histfit(Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV, nbins);
    

    is equivalent to

    data = Wkinet(abs(Wkinet(:,j))>myTolerance, j) * erg2eV;
    H = histfit(data, nbins);
    

    This means below we'll assume data is a vector.


    histfit computes and plots a histogram though histogram, then fits a function to it through fitdist. Since you don't want to plot the histogram itself, just stick to fitdist:

    pd = fitdist(data,'Normal'); % this is the default distribution used in `histfit`, is it correct?
    x = linspace(min(data),max(data),200); % 200 points in the graph, you might want to change this?
    y = pdf(pd,x);
    plot(x,y);
    

    Now it's simple to normalize the plot however we want. For example set the first element to 1:

    pd = fitdist(data,'Normal');
    x = linspace(min(data),max(data),200);
    y = pdf(pd,x);
    y = y/y(1);    % <<< Normalize
    plot(x,y);