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

Problem

You want to overlay a smoothed version of a distribution onto a histogram.

Solution

Call hist with output arguments to obtain the shape of the distribution for a given number of bins.

data=randn(1,100); %Mak some random data

%Let's plot a histogram using the "bar" command
[N,X]=hist(data,15); %Divide data into 15 bins
H=bar(X,N,1); %Plot the histogram. The 1 means bars will will be touching

set(H,'FaceColor','k') %Make the bars black

N=conv(N,ones(1,5),'same')/5; %Smooth the bar heights, averaging over 5 bins
H=line(X,N); %Plot the smoothed line
set(H,'color','r','linewidth',2) %make it red and thicker

Discussion

If you have the Curve Fitting Toolbox then you can use the smooth command instead of the conv command: N=smooth(N,5);. The effect will be much the same, but smooth comes with a variety of different options.

If you want to overlay a particular distribution then try the histfit function from the statistics toolbox.