如何使用interp1d为timeseries数据绘制平滑曲线?

2024-04-19 18:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧,称为new_df:

     period1  intercept     error
0   2018-01-10 -33.707010  0.246193
1   2018-01-11 -36.151656  0.315618
2   2018-01-14 -37.846709  0.355960
3   2018-01-20 -37.170161  0.343631
4   2018-01-26 -31.785060  0.350386
..         ...        ...       ...
121 2020-05-03 -37.654889  0.489900
122 2020-05-06 -36.575763  0.559362
123 2020-06-10 -39.084314  0.756743
124 2020-06-11 -36.240442  0.705487
125 2020-06-14 -45.530748  0.991380

我试图绘制一条平滑曲线(样条曲线),x轴上有“period1”,y轴上有“intercept”。在没有任何插值的情况下,正常绘制:

enter image description here

为了平滑这条曲线,我使用scipy的interp1d函数尝试了以下操作:

from matplotlib import dates
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.plt as plt

x = new_df.period1.values # convert period1 column to a numpy array
y = new_df.intercept.values # convert the intercept column to a numpy array
x_dates = np.array([dates.date2num(i) for i in x]) # period1 values are datetime objects, this line converts them to numbers

f = interp1d(x_dates, y, kind = 'cubic')
x_smooth = np.linspace(x_dates.min(), x_dates.max(), endpoint = True) # unsure if this line is right?

plt.plot(x_dates, y, 'o', x_smooth, f(x_smooth),'--')
plt.xlabel('Date')
plt.ylabel('Intercept')
plt.legend(['data', 'cubic spline'], loc = 'lower right')
plt.show()

这将提供以下输出:

enter image description here

这不是我想要的正确的平滑曲线。我有什么地方做错了吗?另外,如何将XTICK恢复到日期

注意。period1列中的日期之间没有固定的间隔,它们完全是随机的

感谢您的帮助。谢谢


Tags: toimportnumpydfnewnppltarray
1条回答
网友
1楼 · 发布于 2024-04-19 18:05:57

尝试使用数据平滑(即“卷积”),而不是插值(或者除此之外使用)

基本概念很简单-用该点及其周围的平均值替换t点的值

这样做的目的是去除相邻点之间的噪声,使绘图更像数据中的整体趋势

虽然自己编写或使用numpyconvolve很容易,但scipy中有一个专门的方法:savgol_filter提供了一些现成的有用功能

savgol_filterscipy.signal中,因此您可以查看那里的示例

相关问题 更多 >