参考资料:https://blog.csdn.net/weixin_42782150/article/details/107176500
一、Savitzky-Golay 滤波器实现曲线平滑
import numpy as np
import matplotlib.pyplot as plt
# 使用Savitzky-Golay 滤波器后得到平滑图线
from scipy.signal import savgol_filter
Size = 100
x = np.linspace(1, Size, Size)
data = np.random.randint(1, Size, Size)
print(data)
# 可视化图线
plt.plot(x, data)
plt.title('before')
plt.show()
y = savgol_filter(data, 5, 3, mode='nearest')
# 可视化平滑后图线
plt.plot(x, y, 'b', label='savgol')
plt.title('after')
plt.show()
二、插值法对折线进行平滑曲线处理
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import make_interp_spline
x = np.array([6, 7, 8, 9, 10, 11, 12])
y = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])
plt.plot(x, y)
plt.title('before')
plt.show()
x_smooth = np.linspace(x.min(), x.max(), 300) # np.linspace 等差数列,从x.min()到x.max()生成300个数,便于后续插值
y_smooth = make_interp_spline(x, y)(x_smooth)
plt.plot(x_smooth, y_smooth)
plt.title('after')
plt.show()
三、基于Numpy.convolve实现滑动平均滤波
# 实现数据可视化中的数据平滑
import numpy as np
import matplotlib.pylab as plt
'''
其它的一些知识点:
raise:当程序发生错误,python将自动引发异常,也可以通过raise显示的引发异常
一旦执行了raise语句,raise语句后面的语句将不能执行
'''
def moving_average(interval, windowsize):
window = np.ones(int(windowsize)) / float(windowsize)
re = np.convolve(interval, window, 'same')
return re
def LabberRing():
t = np.linspace(-4, 4, 100) # np.linspace 等差数列,从-4到4生成100个数
print('t=', t)
# np.random.randn 标准正态分布的随机数,np.random.rand 随机样本数值
y = np.sin(t) + np.random.randn(len(t)) * 0.1 # 标准正态分布中返回1个,或者多个样本值
print('y=', y)
plt.plot(t, y, 'k') # plot(横坐标,纵坐标, 颜色)
y_av = moving_average(y, 10)
plt.plot(t, y_av, 'b')
plt.xlabel('Time')
plt.ylabel('Value')
# plt.grid()网格线设置
plt.grid(True)
plt.show()
return
LabberRing() # 调用函数