首页 > 解决方案 > 使用 scipy 在 python 中将 sin 曲线拟合到 xslx 数据的问题

问题描述

我正在尝试将 sin 曲线拟合到在 python 中使用 SciPy 从 Excel 工作簿中读取的数据。我认为大多数代码都很好,但是它无法为一组数据点绑定曲线(我只将散点图定义为 [0:20000],因为我有大量数据设置),并且我无法正确获取 p0 参数来获得适合数据的正弦图形状。

我不确定如何使拟合曲线仅在一定范围内工作,以及如何更改参数以拟合初始数据,我尝试了许多参数组合,但它们都在图片。

代码输出以蓝色显示来自 excel 的有界初始数据,曲线以黑色显示

import pandas as pd
from matplotlib import pyplot as plt
from scipy import fftpack as fft
import numpy as np
from scipy import optimize
from scipy.optimize import curve_fit

#%%
loc = "C:/Users/MARK/Downloads/CoupledPendulaDataNEW.xlsx"
sheet_name="25cm In Phase"
file = pd.read_excel(loc, sheet_name=sheet_name)
file.columns=['Time','Phi1','Phi2']
arrTime = np.array(file.Time)
arrPhi1 = np.array(file.Phi1)
arrPhi2 = np.array(file.Phi2)

#%%
plt.figure(figsize=(12,6))
plt.plot(file['Time'][0:20000],file['Phi1'][0:20000], label='Phi 1')

def test_func(x, a, b, c):
    return a * np.sin(b * x) + c

pars, cov = curve_fit(test_func, arrTime, arrPhi1, p0=[1,10,0])
stdevs = np.sqrt(np.diag(cov))
res = arrPhi1 - test_func(arrTime, *pars)

plt.plot(arrTime, test_func(arrTime, *pars), linewidth=2, color='black')

plt.legend(loc='upper left')
plt.xlabel('Time (s)')
plt.ylabel('Voltage signal (V)')
plt.title(sheet_name)

标签: pythonpandasnumpyscipy

解决方案


推荐阅读