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

我一直在尝试使绘图更平滑,就像完成here一样,但是我的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)

但是然后我得到了一个空图,因为我的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.]

解决方法:

您的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.])

首先反转X和Y即可

>>> 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      ])

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

> UnivariateSpline

x : (N,) array_like – 1-D array of independent input data. Must be increasing.

> InterpolatedUnivariateSpline

x : (N,) array_like – Input dimension of data points – must be increasing

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

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

scipy.interpolate.spline的文档含糊不清,建议您可能不支持它.例如,它未在scipy.interpolate main pageinterploation tutorial上列出.source for spline表明它实际上调用splevalsplmake,它们在Additional Tools下列出为:

Functions existing for backward compatibility (should not be used in new code).

我将遵循cricket_007的建议并使用interp1d.这是当前建议的方法,它在detailed examples in both the tutorial和API中有很好的文档说明,并且默认情况下允许对自变量进行不排序(任何顺序)(请参阅API中的authentic_sorted参数).

>>> 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.        ])

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

>>> f = interp1d(X, Y, kind='cubic')

ValueError: x and y arrays must have at least 4 entries

上一篇:使用scipy.io.savemat保存嵌套列表


下一篇:selenium + phantomjs/Chrome