问题描述
我正在尝试将sin函数绘制到数据集。我在网上找到了一个使用scipy.optimize的教程,但是即使我完全复制了代码,它似乎也不起作用。
在顶部:
def func(x,a,b,c,d):
返回a * np.sin(b *(x + c)) + d
最后:
scipy.optimize.curve_fit(func,clean_time,clean_rate)
pylab.show()
输出窗口上没有任何行。
如果有人想要屏幕截图或整个代码,请在下面随意评论。 / p>
谢谢!
当然,它不会绘制任何内容, curve_fit
不会绘制。
在文档中查找,返回值 curve_fit
是带有估计参数的数组和带有估计协方差矩阵的2d数组。您必须自己用估计的参数绘制拟合函数。
我也建议拟合 a * sin(bx + c)+ d
,因为b和c不相关。
这有效:
import matplotlib.pyplot as plt
从numpy导入numpy as np
.random从scipy导入正常
.optimize import curve_fit
x_data = np.linspace(0,2 * np.pi,30)
y_data = np.sin(x_data)+ normal(0,0.2,30)
def func(x,a,b,c,d):
返回a * np.sin(b * x + c)+ d
参数,covariance_matrix = curve_fit(func,x_data ,y_data)
x = np.linspace(min(x_data),max(x_data),1000)
plt.plot(x_data,y_data,'rx',label ='data')
plt.plot(x,func(x,* parameter),'b-',label ='fit')#明星将解压缩参数数组
plt.show()
这是结果:
I am trying to plot a sin function to a data set. I found a tutorial online using scipy.optimize, but it seems not to work even though I copied the code exactly.
At the top:
def func(x, a, b, c, d):
return a * np.sin(b * (x + c)) + d
At the end:
scipy.optimize.curve_fit(func, clean_time, clean_rate)
pylab.show()
There is no line on the output window.
If anyone would like screencaps or the whole code, feel free to comment below.
Thanks!
of course it does not plot anything, curve_fit
does not plot.
Look in the documentation, the return values of curve_fit
are an array with the estimated parameters and a 2d array with the estimated covariance matrix. You have to plot the fit-function with the estimated parameters yourself.
I also would suggest to fit a*sin(bx +c) +d
as then b and c are not correlated.
this works:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import normal
from scipy.optimize import curve_fit
x_data = np.linspace(0, 2*np.pi, 30)
y_data = np.sin(x_data) + normal(0, 0.2, 30)
def func(x, a, b, c, d):
return a * np.sin(b*x + c) + d
parameter, covariance_matrix = curve_fit(func, x_data, y_data)
x = np.linspace(min(x_data), max(x_data), 1000)
plt.plot(x_data, y_data, 'rx', label='data')
plt.plot(x, func(x, *parameter), 'b-', label='fit') # the star is to unpack the parameter array
plt.show()
this is the result:
这篇关于曲线拟合麻烦-Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!