使用python拟合sin曲线

时间:2017-11-02 21:56:06

标签: python curve-fitting

enter image description here

我有两个清单:

# on x-axis:
# list1:
[70.434654, 37.147266, 8.5787086, 161.40877, -27.31284, 80.429482, -81.918106, 52.320129, 64.064552, -156.40771, 12.37026, 15.599689, 166.40984, 134.93636, 142.55002, -38.073524, -38.073524, 123.88509, -82.447571, 97.934402, 106.28793]

# on y-axis:
# list2:
[86683.961, -40564.863, 50274.41, 80570.828, 63628.465, -87284.016, 30571.402, -79985.648, -69387.891, 175398.62, -132196.5, -64803.133, -269664.06, 36493.316, 22769.121, 25648.252, 25648.252, 53444.855, 684814.69, 82679.977, 103244.58]

我需要在通过使用python将list1(在x轴上)与(在y轴上)绘制得到的数据点中拟合正弦曲线a+bsine(2*3.14*list1+c)

我无法获得任何好结果。任何人都可以帮我找到合适的代码,解释......

谢谢!

这是绘制list1(在x轴上)和list2(在y轴上)之后的图表

1 个答案:

答案 0 :(得分:0)

好吧,如果你使用lmfit设置和运行你的健康将如下所示:

xdeg  = [70.434654, 37.147266, 8.5787086, 161.40877, -27.31284, 80.429482, -81.918106, 52.320129, 64.064552, -156.40771, 12.37026, 15.599689, 166.40984, 134.93636, 142.55002, -38.073524, -38.073524, 123.88509, -82.447571, 97.934402, 106.28793]

y = [86683.961, -40564.863, 50274.41, 80570.828, 63628.465, -87284.016, 30571.402, -79985.648, -69387.891, 175398.62, -132196.5, -64803.133, -269664.06, 36493.316, 22769.121, 25648.252, 25648.252, 53444.855, 684814.69, 82679.977, 103244.58]

import numpy as np
from lmfit import Model

import matplotlib.pyplot as plt

def sinefunction(x, a, b, c):
    return a + b * np.sin(x*np.pi/180.0 + c)

smodel = Model(sinefunction)
result = smodel.fit(y, x=xdeg, a=0, b=30000, c=0)

print(result.fit_report())

plt.plot(xdeg, y, 'o', label='data')
plt.plot(xdeg, result.best_fit, '*', label='fit')
plt.legend()
plt.show()

假设您的X数据以度为单位,并且您确实打算将其转换为弧度(因为numpy的sin()函数需要)。

但这只是解决了如何进行拟合的机制(我会将结果显示给你 - 似乎你可能需要这种做法)。

拟合结果很糟糕,因为这些数据不是正弦曲线。它们也没有很好的排序,这对于做适合不是一个问题,但确实让人更难看到发生了什么。