Have a look at
//docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.curve_fit.html,
there is an example at the bottom, which pretty much does what you are after.
Edit: Reply to comment
import matplotlib.pyplot as plt; import numpy as np; import scipy.optimize as opt; # This is the function we are trying to fit to the data. def func(x, a, b, c): return a * np.exp(-b * x) + c # Generate some data, you don't have to do this, as you already have your data xdata = np.linspace(0, 4, 50) y = func(xdata, 2.5, 1.3, 0.5) y_noise = 0.2 * np.random.normal(size=xdata.size) ydata = y + y_noise # Plot the actual data plt.plot(xdata, ydata, ".", label="Data"); # The actual curve fitting happens here optimizedParameters, pcov = opt.curve_fit(func, xdata, ydata); # Use the optimized parameters to plot the best fit plt.plot(xdata, func(xdata, *optimizedParameters), label="fit"); # Show the graph plt.legend(); plt.show();The x, y data are the xdata and ydata variables.
So if you want to use this code, just take out the bit where the data is generated, and define your x, y data arrays as "xdata" and "ydata".
Demos a simple curve fitting
First generate some data
import numpy as np # Seed the random number generator for reproducibility np.random.seed(0) x_data = np.linspace(-5, 5, num=50) y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50) # And plot it import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data)
Now fit a simple sine function to the data
from scipy import optimize def test_func(x, a, b): return a * np.sin(b * x) params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) print(params)
Out:
[3.05931973 1.45754553]
And plot the resulting curve on the data
plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, test_func(x_data, params[0], params[1]), label='Fitted function') plt.legend(loc='best') plt.show()
Total running time of the script: ( 0 minutes 0.026 seconds)
Download Python source code: plot_curve_fit.py
Download Jupyter notebook: plot_curve_fit.ipynb
Gallery generated by Sphinx-Gallery