plot a fit of a normal distribution to the data in x.

def plot_normal(x=None, mean_x=None,std_x=None,color='red',linewidth=2,alpha=1,bins=20,xlim=False,plot_mean=True,plot_std=False,plot_2std=True,figure=None,annotate=True,histogram=True):
    """
    plot a fit of a normal distribution to the data in x.
    """
    import pylab
    if figure is None:
        figure=pylab.figure()
    if mean_x is None:
        #fit maximum likelihood Normal distribution mean to samples X
        mean_x = x.mean() #sample mean
    if std_x is None:
        #fit maximum likelihood Normal distribution standard deviation to samples X
        std_x = x.std()   #sample standard deviation

    xvals=np.arange(mean_x-5*std_x,mean_x+5*std_x,.001)
    yvals=st.norm.pdf(xvals,mean_x,std_x)
    #plot normal distribution:
    ax = pylab.plot(xvals,yvals,color=color,linewidth=linewidth,alpha=alpha)
    if x is not None and histogram:
        #plot histogram of x-values
        pylab.hist(x,bins,normed=True)

    if plot_mean:
        #evaluate distribution at the mean:
        max_cdf=st.norm.pdf(mean_x,mean_x,std_x)
        pylab.plot([mean_x,mean_x],[0,max_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu$', xy=(mean_x+0.6*std_x, 1.0*max_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_std:#plot mean +- 1*standard deviation (64% interval)
        std_cdf=st.norm.pdf(mean_x+std_x,mean_x,std_x)
        pylab.plot([mean_x+std_x,mean_x+std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-std_x,mean_x-std_x],[0,std_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+\sigma$', xy=(mean_x+1.6*std_x, 1.5*std_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if plot_2std:#plot mean +- 2*standard deviations (95% interval)
        std2_cdf=st.norm.pdf(mean_x+2*std_x,mean_x,std_x)
        pylab.plot([mean_x+2*std_x,mean_x+2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        pylab.plot([mean_x-2*std_x,mean_x-2*std_x],[0,std2_cdf],color=color,linewidth=linewidth,alpha=alpha,linestyle="--")
        if annotate:
            pylab.annotate('$\mu+2\sigma$', xy=(mean_x+2.6*std_x, 1.5*std2_cdf),
                horizontalalignment='center', verticalalignment='center',fontsize=15,color=color)
    if xlim: #cut of unused space on y-axis
        pylab.xlim([mean_x-4*std_x,mean_x+4*std_x])
    return figure