I have two 1d arrays shape.x=[701,]
and shape.y=[701,]
. This gives me a curve shown in the image below. How can I make a curve fit for this?
Asked
Active
Viewed 3.7k times
1

DavidG
- 24,279
- 14
- 89
- 82
1 Answers
7
Have a look at
https://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".

Hiho
- 643
- 4
- 8
-
2That example is pretty complex for me as I am new in python. Can you tell me where should I put my x and y values if I use the code of your given example. – May 15 '17 at 09:32