我有一组数据,我想使用正弦函数来拟合。因此我写了以下代码:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def sin_curve(rad, a, b, c, d):
result = []
for value in rad:
outcome = float(a*np.sin(b*value + c) + d)
result.append(outcome)
return result
# X data => polangle_rad, Y data => three_ara
[a_300, b_300, c_300, d_300], var_300 = curve_fit(sin_curve, polangle_rad, three_ara, p0=[10,2,-0.5,75])
polplt_xrange = np.arange(0,2*np.pi+unit,unit)
# Plotting
plt.figure()
three_line,_ = ax.plot(polangle_rad, three_ara, 'bo', polplt_xrange, np.array(sin_curve(polplt_xrange, a_300, b_300, c_300, d_300)), 'b-')
plt.show()
我得到的情节是这样的;拟合曲线由蓝色实线给出,而数据点由蓝色点给出。
从图中我们可以看到拟合曲线略微向左旋转。有没有更好的方法来适应曲线?
答案 0 :(得分:0)
该问题不可重复。使用生成的值时,拟合是完美的。因此,该方法工作正常。
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def sin_curve(rad, a, b, c, d):
result = []
for value in rad:
outcome = float(a*np.sin(b*value + c) + d)
result.append(outcome)
return result
xval = np.linspace(0,2*np.pi,16)
yval = -10*np.sin(2*xval-1.5)+75
# X data => polangle_rad, Y data => three_ara
[a_300, b_300, c_300, d_300], var_300 = curve_fit(sin_curve, xval,
yval, p0=[10,2,-0.5,75])
print [a_300, b_300, c_300, d_300]
# [-9.9999999999999556, 1.9999999999999991, -1.4999999999999984, 75.0]
polplt_xrange = np.linspace(0,2*np.pi,100)
# Plotting
fig = plt.figure()
ax = fig.add_subplot(121, projection="polar")
ax2 = fig.add_subplot(122)
p, = ax.plot(xval, yval, 'bo')
y = np.array(sin_curve(polplt_xrange, a_300, b_300, c_300, d_300))
line, = ax.plot(polplt_xrange,y , 'b-')
ax.set_ylim(None, y.max()*1.1)
ax2.plot(xval, yval, 'bo')
ax2.plot(polplt_xrange,y , 'b-')
plt.tight_layout()
plt.show()