Gaussian fit for Python

前端 未结 6 647
我寻月下人不归
我寻月下人不归 2020-11-27 04:06

I\'m trying to fit a Gaussian for my data (which is already a rough gaussian). I\'ve already taken the advice of those here and tried curve_fit and leasts

6条回答
  •  面向向阳花
    2020-11-27 04:39

    Here is corrected code:

    import pylab as plb
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    from scipy import asarray as ar,exp
    
    x = ar(range(10))
    y = ar([0,1,2,3,4,5,4,3,2,1])
    
    n = len(x)                          #the number of data
    mean = sum(x*y)/n                   #note this correction
    sigma = sum(y*(x-mean)**2)/n        #note this correction
    
    def gaus(x,a,x0,sigma):
        return a*exp(-(x-x0)**2/(2*sigma**2))
    
    popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])
    
    plt.plot(x,y,'b+:',label='data')
    plt.plot(x,gaus(x,*popt),'ro:',label='fit')
    plt.legend()
    plt.title('Fig. 3 - Fit for Time Constant')
    plt.xlabel('Time (s)')
    plt.ylabel('Voltage (V)')
    plt.show()
    

    result:
    enter image description here

提交回复
热议问题