【发布时间】: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