I fit a function (gauss curve) to some datapoints using lm fit.
# prepare data
data = pd.read_csv("data.csv")
X = np.array(data.iloc[:,0])
Y = np.array(data.iloc[:,1])
def Gauss(x,y0,a,mu,sigma):
return y0+a/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-mu)**2/(2*sigma**2))
gmodel = Model(Gauss)
result = gmodel.fit(Y, x=X, y0=0, a=1, mu=1, sigma=1)
conf = result.eval_uncertainty(sigma=1)
print(result.fit_report())
So far so good. Now I would like to plot the data and the model
x = np.linspace(min(X), max(X))
plt.figure(
num=1,
figsize=(10,6),
facecolor='white')
plt.plot(X, Y, 'bo', label='Data')
# This does not work
plt.plot(x, result.init_fit, 'k--', label='Initial guess')
plt.plot(x, result.best_fit, 'r-', label='Best fit')
plt.fill_between(x, result.best_fit-conf, result.best_fit+conf, color='black', label='Confidence band')
plt.legend(loc=2)
However this does not work, since result.init_fit
and result.best_fit
and most importantly conf
are evaluating the results only at the datapoints I have fitted them to, not all datapoints in x
. So how do I evaluate these for all datapoints in x
?
You can just re-evaluate your model with the new x
values with
x_new = np.linspace(min(X), max(X), 1001) # or whatever you want
result_new = result.eval(x=x_new)
To evaluate the result not using the best-fit parameters (which the above will do by default), but with the initial parameters, use
init_new = result.eval(params=result.init_params, x=x_new)