【问题标题】:How to plot a smooth curve using interp1d for time-series data?如何使用 interp1d 为时间序列数据绘制平滑曲线?
【发布时间】:2020-09-27 22:28:52
【问题描述】:

我有以下数据框,称为 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”。正常绘制,没有任何插值:

为了平滑这条曲线,我使用 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()

这给出了输出:

这不是我想要得到的正确平滑曲线。我在某处做错了什么吗?另外,我怎样才能将 xticks 恢复为日期?

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

感谢任何帮助。谢谢!

【问题讨论】:

  • 我猜这取决于插值的类型,也许另一个可以工作。

标签: python scipy time-series interpolation


【解决方案1】:

尝试使用数据平滑(即“卷积”),而不是插值(或另外使用)。

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

这将做的是去除相邻点之间的噪音,并使图看起来更像数据中的整体趋势。

虽然自己编写或使用 numpy convolve 很容易,但 scipy 中有一个专门的方法:savgol_filter,它提供了一些开箱即用的有用功能。

savgol_filter 位于 scipy.signal 中,因此您可以查看那里的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2017-01-14
    • 2021-02-18
    • 2012-06-09
    相关资源
    最近更新 更多