使用matplotlib进行曲线拟合 [英] Curve fitting using matplotlib
本文介绍了使用matplotlib进行曲线拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个1d数组shape.x=[701,]
和shape.y=[701,]
.这给了我一条曲线,如下图所示.我怎样才能使曲线拟合呢?
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?
推荐答案
看看
https://docs .scipy.org/doc/scipy-0.19.0/reference/generation/scipy.optimize.curve_fit.html ,
底部有一个示例,几乎可以满足您的要求.
there is an example at the bottom, which pretty much does what you are after.
回复评论
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变量.
The x, y data are the xdata and ydata variables.
因此,如果要使用此代码,只需取出生成数据的位,然后将x,y数据数组定义为"xdata"和"ydata"即可.
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".
这篇关于使用matplotlib进行曲线拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文