recipes : Plotting : Distributions : Overlay a Gaussian distribution onto a histogram

Problem

How do I overlay a Gaussian bell-curve onto a histogram? histogram.

Solution

We will use the fitdist function from the Statistics Toolbox to quickly fit a Gaussian to a histogram.

%Generate and plotsome random data
r=randn(100,1); 
hist(r,20)

%Make the plot look prettier (gray faces)
h=findobj(gca,'type','patch')
set(h,'FaceColor',[1,1,1]*0.5)

%Now fit a Gaussian
pd=fitdist(r(:),'normal')

pd = 
  NormalDistribution

  Normal distribution
       mu = 0.0700439   [-0.111376, 0.251463]
    sigma =  0.914313   [0.802773, 1.06213]

%pd is a model object that contains the parameters of the fit.
%We now use the model to calculate the values for the Gaussian
%for our data.  

x=-3:0.1:3;  
PDF=pdf(pd,x); %PDF is a vector of y values: it's our fit

%Now overlay the fit
PDF=PDF/max(PDF); %normalise
%scale to y axis
y=ylim;
PDF=PDF*y(2);

hold on
plot(x,PDF,'r-','LineWidth',2)
hold off

gaussian and historgram

Discussion

Easy! Just a few lines of code and we have a nice fit to our data. If you want to fit a variety of different distributions with ease then check out this great submission at the File Exchange. That also requires the Statistics Toolbox, but what if you don't have this? Help is at hand! Check out this, this, and this.