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 code:
import pylab, numpy
from scipy.optimize import curve_fit
x=numpy.array(range(10))
y=numpy.array([0,1,2,3,4,5,4,3,2,1])
n=len(x)
mean=sum(y)/n
sigma=sum(y-mean)**2/n
def gaus(x,a,x0,sigma):
return a*numpy.exp(-(x-x0)**2/(2*sigma**2))
popt, pcov=curve_fit(gaus,x,y,p0=[1,mean,sigma])
pylab.plot(x,y,'r-',x,y,'ro')
pylab.plot(x,gaus(x,*popt),'k-',x,gaus(x,*popt),'ko')
pylab.show()
The code fits a gaussian to an n shaped curve but if I change y to y=numpy.array([5,4,3,2,1,2,3,4,5,6]) then it return some error: Optimal parameters not found: Number of calls to function has reached maxfev = 800.
What do I have to change/adjust in the code to fit a U shaped gaussian ? Thanks.