您现在的位置是:网站首页> 编程资料编程资料
Python曲线平滑的实现示例_python_
2023-05-26
297人已围观
简介 Python曲线平滑的实现示例_python_
在编写测试程序的时候,由于数据帧数多的原因,导致生成的曲线图比较难看,如下图:

由于高频某些点的波动导致高频曲线非常难看,因此需要对曲线做平滑处理,让曲线过渡更平滑。对曲线进行平滑处理,这里推荐使用Savitzky-Golay 滤波器,可以在scipy库里直接调用,不需要再定义函数。
Python中 Savitzky-Golay 滤波器调用如下:
tmp_smooth = scipy.signal.savgol_filter(tmp,53,3)
scipy函数解释:
scipy.signal.savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode=‘interp’, cval=0.0)[source]
Apply a Savitzky-Golay filter to an array.
This is a 1-d filter. If x has dimension greater than 1, axis determines the axis along which the filter is applied.
在scipy函数解释中,x为原始数据,即上面代码中的tmp数据。window_length是窗口长度,该值需为正奇整数。polyorder为对窗口内的数据点进行k阶多项式拟合,k的值需要小于window_length。
现在看一下window_length和k这两个值对曲线的影响。
(1) 首先是window_length对曲线的平滑作用,代码如下:
tmp_smooth1 = scipy.signal.savgol_filter(tmp,21,3) tmp_smooth2 = scipy.signal.savgol_filter(tmp,53,3) plt.semilogx(f,tmp*0.5,label = 'mic'+str(num+1)) plt.semilogx(f,tmp_smooth1*0.5,label = 'mic'+str(num+1)+'拟合曲线-21',color = 'red') plt.semilogx(f,tmp_smooth2*0.5,label = 'mic'+str(num+1)+'拟合曲线-53',color = 'green')

可以看到,window_length的值越小,曲线越贴近真实曲线;window_length值越大,平滑效果越厉害。
(2) 再看k值对曲线的影响,代码如下:
tmp_smooth1 = scipy.signal.savgol_filter(tmp,21,3) tmp_smooth2 = scipy.signal.savgol_filter(tmp,53,3) plt.semilogx(f,tmp*0.5,label = 'mic'+str(num+1)) plt.semilogx(f,tmp_smooth1*0.5,label = 'mic'+str(num+1)+'拟合曲线-21',color = 'red') plt.semilogx(f,tmp_smooth2*0.5,label = 'mic'+str(num+1)+'拟合曲线-53',color = 'green')
生成曲线图如下:

可以看到,k值越大,曲线越贴近真实曲线;k值越小,曲线平滑越厉害。另外,当k值较大时,受窗口长度限制,拟合会出现问题,高频曲线会变成直线,如下图所示:

参考资源
[1] python 平滑_Python 生成曲线进行快速平滑处理
[2] Savitzky-Golay平滑滤波的python实现
到此这篇关于Python曲线平滑的实现示例的文章就介绍到这了,更多相关Python曲线平滑内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- Python Matplotlib绘制动画的代码详解_python_
- 关于pytest结合csv模块实现csv格式的数据驱动问题_python_
- Python中的协程(Coroutine)操作模块(greenlet、gevent)_python_
- Pandas实现批量拆分与合并Excel的示例代码_python_
- Python实现仓库管理系统_python_
- Python中的线程操作模块(oncurrent)_python_
- Python 迭代器Iterator详情_python_
- 详解Python中的PyInputPlus模块_python_
- python实现班级档案管理系统_python_
- Python中的进程操作模块(multiprocess.process)_python_
