Reputation: 431
I was able to figure out how to plot the histogram of data using this
histogram(data,'Normalization','pdf')
but how do I plot the histogram of data with the best fit distribution overlaid on it? I also need to include the axis labels with units.
Upvotes: 1
Views: 248
Reputation: 1845
It depends ofcourse on what distribution you have. Here I fit a normal distribution. It is often best to fit the cdf of your data, not de pdf. The fit parameters are the same ofcourse. So you can just as well plot the pdf afterwards.
data = randn(1,1E3);
fig=figure(1);clf;hold on
H = histogram(data,'Normalization','pdf'); %you have this as well
%pdf and cdf of normal distribution
npdf = @(x,p) 1/(sqrt(2*p(2)^2*pi)) * exp(-(x-p(1)).^2 / (2*p(2)^2));
ncdf = @(x,p) 0.5*(1+erf((x-p(1)) / (p(2)*sqrt(2))));
%generate and show cdf of the data
data = sort(data);
x = linspace(0,1,1E3);
figure();plot(data,x); %cdf
%fit cdf
ssqe = @(x,y,p) sum((y-ncdf(x,p)).^2); %sum of squared error
p = [1 1]; %starting values
p = fminsearch(@(p) ssqe(data,x,p), p); %fit\
%plot pdf of the fit
figure(fig)
plot(data,npdf(data,p),'--r')
Upvotes: 1