Jack.O.
Jack.O.

Reputation: 171

How do i get a smooth fit for my data points, using "scipy.optimize.curve_fit"?

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()

enter image description here

I would acutally expect some kind of a smooth curve. Can someone explain what I am doing wrong here?

Upvotes: 4

Views: 2104

Answers (1)

jeremycg
jeremycg

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')

smooth

Upvotes: 6

Related Questions