Search code examples
matlabhistogramnormalizebins

Histogram with logarithmic bins and normalized


I want to make a histogram of every column of a matrix, but I want the bins to be logarithmic and also normalized. And after I create the histogram I want to make a fit on it without showing the bars. This is what I have tried:

y=histogram(x,'Normalized','probability');

This gives me the histogram normalized, but I don't know how to make the bins logarithmic.


Solution

  • There are two different ways of creating a logarithmic histogram:

    1. Compute the histogram of the logarithm of the data. This is probably the nicest approach, as you let the software decide on how many bins to create, etc. The x-axis now doesn't match your data, it matches the log of your data. For fitting a function, this is likely beneficial, but for display it could be confusing. Here I change the tick mark labels to show the actual value, keeping the tick marks themselves at their original values:

      y = histogram(log(x),'Normalization','probability');
      h = gca;
      h.XTickLabels = exp(h.XTick);
      
    2. Determine your own bin edges, on a logarithmic scale. Here you need to determine how many bins you need, depending on the number of samples and the distribution of samples.

      b = 2.^(1:0.25:3);
      y = histogram(x,b,'Normalization','probability');
      set(gca,'XTick',b) % This just puts the tick marks in between bars so you can see what we did.
      

    Method 1 lets MATLAB determine number of bins and bin edges automatically depending on the input data. Hence it is not suitable for creating multiple matching histograms. For that case, use method 2. The in edges can be obtained more simply this way:

    N = 10;         % number of bins
    start = min(x); % first bin edge
    stop = max(x);  % last bin edge
    b = 2.^linspace(log2(start),log2(stop),N+1);