使用样条线+日期时间对象的平滑线不起作用

Aim*_*Hat 4 python datetime interpolation matplotlib scipy

我一直在尝试使绘图更加平滑,就像在这里所做的那样,但是我的Xs是与linspace不兼容的日期时间对象。

我将X转换为matplotlib日期:

Xnew = matplotlib.dates.date2num(X)
X_smooth = np.linspace(Xnew.min(), Xnew.max(), 10)
Y_smooth = spline(Xnew, Y, X_smooth)
Run Code Online (Sandbox Code Playgroud)

但是然后我得到了一个空图,因为我的Y_smooth是

[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]

由于某些未知的原因。

我该如何进行这项工作?

编辑

这是我打印变量时得到的,但没有发现异常:

X : [datetime.date(2016, 7, 31), datetime.date(2016, 7, 30), datetime.date(2016, 7, 29)]
X new: [ 736176.  736175.  736174.]
X new max: 736176.0
X new min: 736174.0
XSMOOTH [ 736174.          736174.22222222  736174.44444444  736174.66666667
  736174.88888889  736175.11111111  736175.33333333  736175.55555556
  736175.77777778  736176.        ]
Y [711.74, 730.0, 698.0]
YSMOOTH [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ski 5

您的X值将反转,scipy.interpolate.spline要求自变量单调递增,并且不建议使用此方法- interp1d改为使用(请参见下文)。

>>> from scipy.interpolate import spline
>>> import numpy as np
>>> X = [736176.0, 736175.0, 736174.0]  # <-- your original X is decreasing
>>> Y = [711.74, 730.0, 698.0]
>>> Xsmooth = np.linspace(736174.0, 736176.0, 10)
>>> spline(X, Y, Xsmooth)
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
Run Code Online (Sandbox Code Playgroud)

反向XY首先,它的工作原理

>>> spline(
...     list(reversed(X)),  # <-- reverse order of X so also
...     list(reversed(Y)),  # <-- reverse order of Y to match
...     Xsmooth
... )
array([  698.        ,   262.18297973,   159.33767533,   293.62017489,
         569.18656683,   890.19293934,  1160.79538066,  1285.149979  ,
        1167.41282274,   711.74      ])
Run Code Online (Sandbox Code Playgroud)

请注意,许多样条插值方法需要X单调增加:

x(N,)array_like-独立输入数据的一维数组。必须增加。

x(N,)array_like-数据点的输入维数–必须增加

默认顺序scipy.interpolate.spline为立方。因为只有3个数据点,所以三次样条(order=3)和二次样条(order=2)之间存在较大差异。下图显示了不同阶样条之间的差异;注意:使用100点可以使拟合曲线更加平滑

scipy.interpolate.spline

的文档scipy.interpolate.spline含糊不清,建议您可能不支持该文档。例如,它没有显示在scipy.interpolate主页上交际教程中。显示其实际调用的源,splinesplevalsplmake在“ 其他工具”下列出为:

为向后兼容而存在的功能(不应在新代码中使用)。

我会遵循cricket_007的建议和使用interp1d。这是当前建议的方法,在教程和API 中都有详细的示例进行了很好的说明,并且默认情况下允许对自变量进行不排序(任何顺序)(请参阅assume_sortedAPI中的参数)。

>>> from scipy.interpolate import interp1d
>>> f = interp1d(X, Y, kind='quadratic')
>>> f(Xsmooth)
array([ 711.74      ,  720.14123457,  726.06049383,  729.49777778,
        730.45308642,  728.92641975,  724.91777778,  718.4271605 ,
        709.4545679 ,  698.        ])
Run Code Online (Sandbox Code Playgroud)

如果数据排名不足,也会引发错误。

>>> f = interp1d(X, Y, kind='cubic')
Run Code Online (Sandbox Code Playgroud)

ValueError:x和y数组必须至少包含4个条目