Fitting a histogram with python

后端 未结 5 1286
梦毁少年i
梦毁少年i 2020-11-28 02:18

I have a histogram

H=hist(my_data,bins=my_bin,histtype=\'step\',color=\'r\')

I can see that the shape is almost gaussian but I would like t

5条回答
  •  被撕碎了的回忆
    2020-11-28 02:37

    Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).

    from pylab import *
    from numpy import loadtxt
    from scipy.optimize import leastsq
    
    fitfunc  = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
    errfunc  = lambda p, x, y: (y - fitfunc(p, x))
    
    filename = "gaussdata.csv"
    data     = loadtxt(filename,skiprows=1,delimiter=',')
    xdata    = data[:,0]
    ydata    = data[:,1]
    
    init  = [1.0, 0.5, 0.5, 0.5]
    
    out   = leastsq( errfunc, init, args=(xdata, ydata))
    c = out[0]
    
    print "A exp[-0.5((x-mu)/sigma)^2] + k "
    print "Parent Coefficients:"
    print "1.000, 0.200, 0.300, 0.625"
    print "Fit Coefficients:"
    print c[0],c[1],abs(c[2]),c[3]
    
    plot(xdata, fitfunc(c, xdata))
    plot(xdata, ydata)
    
    title(r'$A = %.3f\  \mu = %.3f\  \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));
    
    show()
    

    Output:

    A exp[-0.5((x-mu)/sigma)^2] + k 
    Parent Coefficients:
    1.000, 0.200, 0.300, 0.625
    Fit Coefficients:
    0.961231625289 0.197254597618 0.293989275502 0.65370344131
    

    gaussian plot with fit

提交回复
热议问题