【问题标题】:Spline interpolation with datetime带日期时间的样条插值
【发布时间】:2018-05-04 09:18:36
【问题描述】:

我正在用 Python 编写一个应用程序,它收集有关温度和时间的信息并将它们绘制在图表中。

在这里看到Smooth line with spline + datetime objects doesn't work

我想插入几个温度值以使图形温度时间更平滑。

此函数检索温度和时间的值,并将它们放入与位置(卧室和厨房)相关的数组中:

    xTemp, yTemp = dataList[1].split(',')
    xTime, yTime = dataList[3].split(',')

    t = datetime.fromtimestamp(float(xTime)).strftime('%Y-%m-%d %H:%M:%S')  # get time string
    st = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')  # get datetime from time string

    x.append(st)
    y.append(xTemp)
    X = np.array(x)
    Y = np.array(y)
    Xnew = matplotlib.dates.date2num(X)

    if(len(X) >= 5):
        X_smooth = np.linspace(Xnew.min(), Xnew.max(), 10)
        Y_smooth = interp1d(X, Y, X_smooth)  
        # , assume_sorted = True, kind = 'quadratic')
        a.plot(X_smooth, Y_smooth)

我遇到了这个错误:

NotImplementedError: [736817.73790509 736817.73791152 736817.73791795 736817.73792438
 736817.73793081 736817.73793724 736817.73794367 736817.7379501
 736817.73795653 736817.73796296] is unsupported: Use fitpack routines for other types.

你能帮帮我吗?谢谢

【问题讨论】:

  • 哪一行会抛出这个错误?我建议提供尽可能短但可运行的代码。看来,您的代码处于循环中(是吗?)
  • interp1d的插值
  • 在这种情况下,请获取 X、Y 和 X_smooth(使用调试器或仅打印它们)并将上面的代码替换为这些值。
  • @betonalpfa 是的,我的代码在一个 for 循环中,它从 json 文件中检索 ip 和端口,并执行一个请求 witch CoAP 协议(​​实际上是套接字),这样我就可以动态更新每秒或更少的图表

标签: python datetime tkinter spline


【解决方案1】:

你对函数interp1d的使用是错误的。来自文档:

该类返回一个函数,其调用方法使用插值来查找新点的值

正如您从同一页面上的示例中看到的那样,您应该只使用您拥有的 x 和 y 值调用 interp1d。这将返回一个函数,您可以向该函数传递新的 x 值并返回插值后的 y 值:

x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y)

xnew = np.arange(0, 9, 0.1)
ynew = f(xnew)   # use interpolation function returned by `interp1d`

所以在你的情况下,这将是:

f = interp1d(X, Y)
X_smooth = np.linspace(Xnew.min(), Xnew.max(), 10)
Y_smooth = f(X_smooth) 

【讨论】:

  • 真的非常感谢 fhdrsdg 和 @betontalpfa,我终于解决了我的问题,但我不得不使用 len(Xnew) > 4 来避免出现 ValueError: number of variables at boundary
  • 我正在尝试另一个问题,但很少:interpolation = interp1d(Xnew, Y, kind='quadratic') ValueError: Expect x to be a 1-D sorted array_like。我不知道为什么,但它很少发生,但 Xnew 是通过附加新的日期时间生成的日期,这些日期时间肯定是有序的
  • 你确定没有重复的值,因为我认为这会产生同样的错误。如果不是这种情况,您可能应该提出一个包含所有相关信息的新问题。
【解决方案2】:

interp1d 返回一个函数。请尝试以下操作:

Y_smooth = interp1d(X, Y)
print (Y_smooth(X_smooth[0]))

【讨论】:

  • 结果是我'不能比较 datetime.datetime 和 float',我应该改用 Xnew
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多