Reputation: 171
I want to fit some data points using scipy.optimize.curve_fit
. Unfortunately I get an unsteady fit and I do not know why.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
M = np.array([730,910,1066,1088,1150], dtype=float)
V = np.array([95.71581923, 146.18564513, 164.46723727, 288.49796413, 370.98703941], dtype=float)
def func(x, a, b, c):
return a * np.exp(b * x) + c
popt, pcov = curve_fit(func, M, V, [0,0,1], maxfev=100000000)
print(*popt)
fig, ax = plt.subplots()
fig.dpi = 80
ax.plot(M, V, 'go', label='data')
ax.plot(M, func(M, *popt), '-', label='fit')
plt.xlabel("M")
plt.ylabel("V")
plt.grid()
plt.legend()
plt.show()
I would acutally expect some kind of a smooth curve. Can someone explain what I am doing wrong here?
Upvotes: 4
Views: 2104
Reputation: 24945
You are only plotting the same x points as the original data in your call:
ax.plot(M, V, 'go', label='data')
ax.plot(M, func(M, *popt), '-', label='fit')
To fix this, you can use a wider range - here we use all the values from 700 to 1200:
toplot = np.arange(700,1200)
ax.plot(toplot, func(toplot, *popt), '-', label='fit')
Upvotes: 6