Skip to content Skip to sidebar Skip to footer

Fitting A Gaussian To A Curve In Python

I want to fit a gaussian to a curve using python . I found a solution here somewhere but it only seems to work for an n shaped gaussian , not for a u shaped gaussian . Here is the

Solution 1:

The functional form of your fit is wrong. Gaussian's are expected to go to 0 at the tails regardless of whether it is an n or u shape, but yours goes to ~5.

If you introduce an offset into your equation, and choose reasonable initial values, it works. See code below:

import pylab, numpy
from scipy.optimize import curve_fit

x=numpy.array(range(10))
y=numpy.array([5,4,3,2,1,2,3,4,5,6])

n=len(x)
mean=sum(y)/n
sigma=sum(y-mean)**2/n

defgaus(x,a,x0,sigma,c):
    return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c

popt, pcov=curve_fit(gaus,x,y,p0=[-1,mean,sigma,-5])

pylab.plot(x,y,'r-',x,y,'ro')
pylab.plot(x,gaus(x,*popt),'k-',x,gaus(x,*popt),'ko')
pylab.show()

Solution 2:

Perhaps you could invert your values, fit to a 'n' shaped gaussian, and then invert the gaussian.

Post a Comment for "Fitting A Gaussian To A Curve In Python"