[SciPy-user] wxplt histogram + normal fit function (histfit)

Sajec, Mike TQO msajec at tqs.com
Wed Aug 27 19:01:00 EDT 2003


I wrote this function to create histograms with normal fits, and thought it
may be useful to other scipy users.  It requires matplotlib for the normal
pdf function (http://matplotlib.sourceforge.net/).  Here it is:

Best Regards,
Mike

#***************************************************************************
****
# Module: tqplots.py
# Author: Mike Sajec
# Date: 8-13-03
#
# Change Log:
# 8-13-03 - added first function: histfit
#***************************************************************************
****

from matplotlib import mlab
from scipy import *
from chaco import *
from chaco import wxplt as plt
import RandomArray as ra

def histfit(data):
    """histfit(data)
       data = a 1-dimensional list or numpy array of numbers"""    
    #data for testing...
    #data = ra.normal(0,3,100)

    mu = mlab.mean(data)
    sigma = mlab.std(data)

    mhist = mlab.hist(data)
    xhist = mhist[1]
    yhist = mhist[0]

    #put xhist & yhist into a list of tuple pairs    
    histvalues=[]
    for ii in range(len(xhist)):
        histvalues.append((xhist[ii],yhist[ii]))
    
    histplot = plt.PlotValue(histvalues, type='bar')

    f1 = plt.figure()
    f1.canvas.add(histplot)
    plt.hold()

    # Plot the normal fit curve
    xnormfit = arange(mu-4*sigma,mu+4*sigma,(8*sigma/100))  
    ynormfit = mlab.normpdf(xnormfit,mu,sigma)  # 
    ynormfit = ynormfit/max(ynormfit)*max(yhist) #normalize

    #put xnormfit & ynormfit into a list of tuple pairs    
    fitvalues=[]
    for ii in range(len(xnormfit)):
        fitvalues.append((xnormfit[ii],ynormfit[ii]))

    fitplot = plt.PlotValue(fitvalues,type='line')
    f1.canvas.add(fitplot)
    
    #Plot the limits
    #plt.plot((mu-4*sigma)*ones(2),[0,max(yhist)])   # plot lower spec limit
    #plt.plot((mu+4*sigma)*ones(2),[0,max(yhist)])   # plot upper spec limit

    return f1




More information about the SciPy-User mailing list