Skip to content

Instantly share code, notes, and snippets.

@habi
Created January 29, 2016 14:37
Show Gist options
  • Save habi/66be86bfb94a96a51245 to your computer and use it in GitHub Desktop.
Save habi/66be86bfb94a96a51245 to your computer and use it in GitHub Desktop.
import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
# Define model function to be used to fit to the data above:
def gauss(x, *p):
A, mu, sigma = p
return A*numpy.exp(-(x-mu)**2/(2.*sigma**2))
xdata = numpy.linspace(-5,5,100)
y = gauss(xdata,2,2,0.9)
ydata = y + 0.1 * numpy.random.normal(size=len(xdata))
# Fit
# p0 is the initial guess for the fitting coefficients (A, mu and sigma above)
p0 = [1, 0, 1]
coeff, var_matrix = curve_fit(gauss, xdata, ydata, p0=p0)
plt.plot(ydata, label='Test data')
plt.plot(gauss(xdata, *coeff), label='Gaussian fit')
plt.legend(loc='best')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment