#270 Fitting noisy data with a Gaussian equation using python

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Creating a function to model and create data
def func(x, a, b, c):
    return a*np.exp(-(x-b)**2/(2*c**2))

x = np.linspace(0, 10, 100)
y = func(x, 1, 5, 2)

# Adding noise to the data
yn = y + 0.2 * np.random.normal(size=len(x))

# Executing curve_fit on noisy data
popt, pcov = curve_fit(func, x, yn)

fig,ax = plt.subplots()
ax.plot(x,y,'b-',label='data')
ax.plot(x,yn,'.',c='red',label='data with noise')
ax.plot(x, func(x, *popt),'g--',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.xlabel('y')
plt.legend()
plt.savefig('ex270.png', dpi=90)
plt.show()