使用matplotlib进行曲线拟合

时间:2017-05-14 23:47:33

标签: python numpy matplotlib scipy

我有两个1d数组shape.x=[701,]shape.y=[701,]。这给了我一条如下图所示的曲线。如何使曲线适合这个?

enter image description here

1 个答案:

答案 0 :(得分:3)

看看

https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.curve_fit.html

底部有一个例子,几乎就是你所追求的。

编辑:回复评论

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

x,y数据是xdata和ydata变量。

因此,如果您想使用此代码,只需取出生成数据的位,并将x,y数据数组定义为“xdata”和“ydata”。