Skip to main content
 首页 » 编程设计

python之如何平滑曲线

2025年05月04日20sky-heaven

我正在使用以下代码从我的两列原始数据(x=time,y=|float data|)中绘制一条曲线。它绘制的图形是一个粗糙的边缘图。是否有可能对这些数据进行平滑处理?我附上代码、数据和曲线。

from datetime import datetime 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates 
from matplotlib import style 
 
# changing matplotlib the default style 
matplotlib.style.use('ggplot') 
#one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'} 
plt.rcParams['lines.linewidth']=1 
plt.rcParams['axes.facecolor']='.3' 
plt.rcParams['xtick.color']='b' 
plt.rcParams['ytick.color']='r' 
 
 
 
x,y= np.loadtxt('MaxMin.txt', dtype=str, unpack=True) 
x = np.array([datetime.strptime(i, "%H:%M:%S.%f") for i in x]) 
y = y.astype(float) 
 
# naming the x axis  
plt.xlabel('<------Clock-Time(HH:MM:SS)------>')  
# naming the y axis  
plt.ylabel('Acceleration (m/sq.sec)')  
# giving a title to my graph  
plt.title('Sample graph!') 
# plotting the points  
plt.plot(x, y) 
# beautify the x-labels 
plt.gcf().autofmt_xdate() 
#Custom Format 
loc = matplotlib.dates.MicrosecondLocator(1000000) 
plt.gca().xaxis.set_major_locator(loc) 
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M:%S')) 
# function to show the plot  
plt.show() 

我搜索过类似的线程,但它们使用的数学概念让我难以理解。所以我无法确定我的数据究竟需要做什么。

Generated Graph from RAW data

我还提供了示例数据文件,以便您可以在最后重新构建它。

Get Data File

附言。即使在使用之后,我也无法将图表中的线条颜色从默认红色更改为

plt.rcParams['lines.color']='g' 

尽管在这种情况下这是一个小问题。

请您参考如下方法:

输入的数据有错误的时间戳,原作者在格式化毫秒时应该使用零填充(%03d)。

[...] 
10:27:19.3 9.50560385141 
10:27:19.32 9.48882194058 
10:27:19.61 9.75936468731 
10:27:19.91 9.96021690527 
10:27:19.122 9.48972151383 
10:27:19.151 9.49265161533 
[...] 

我们需要先解决这个问题:

x, y = np.loadtxt('MaxMin.txt', dtype=str, unpack=True) 
 
# fix the zero-padding issue 
x_fixed = [] 
for xx in x: 
    xs = xx.split(".") 
    xs[1] = "0"*(3-len(xs[1])) + xs[1] 
    x_fixed.append(xs[0] + '.' + xs[1]) 
 
x = np.array([datetime.strptime(i, "%H:%M:%S.%f") for i in x_fixed]) 
y = y.astype(float) 

然后您可以使用平滑核(例如移动平均线)来平滑数据:

window_len = 3 
kernel = np.ones(window_len, dtype=float)/window_len 
y_smooth = np.convolve(y, kernel, 'same')