Matlab: plotting frequency distribution with a curve

前端 未结 2 454
梦谈多话
梦谈多话 2021-01-26 19:00

I have to plot 10 frequency distributions on one graph. In order to keep things tidy, I would like to avoid making a histogram with bins and would prefer having lines that follo

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 19:59

    How about interpolating with splines?

    nbins = 10; %// number of bins for original histogram
    n_interp = 500; %// number of values for interpolation
    [counts, bins] = hist(data, nbins);
    bins_interp = linspace(bins(1), bins(end), n_interp);
    counts_interp = interp1(bins, counts, bins_interp, 'spline');
    plot(bins, counts) %// original histogram
    figure
    plot(bins_interp, counts_interp) %// interpolated histogram
    

    Example: let

    data = randn(1,1e4);
    

    Original histogram:

    enter image description here

    Interpolated:

    enter image description here

    Following your code, the y axis in the above figures gives the count, not the probability density. To get probability density you need to normalize:

    normalization = 1/(bins(2)-bins(1))/sum(counts);
    plot(bins, counts*normalization) %// original histogram
    plot(bins_interp, counts_interp*normalization) %// interpolated histogram
    

    Check: total area should be approximately 1:

    >> trapz(bins_interp, counts_interp*normalization)
    ans =
        1.0009
    

提交回复
热议问题