python中平滑matplotlib绘图的日期时间插值

python中平滑matplotlib绘图的日期时间插值,python,datetime,numpy,matplotlib,scipy,Python,Datetime,Numpy,Matplotlib,Scipy,我有如下日期时间和值的列表: import datetime x = [datetime.datetime(2016, 9, 26, 0, 0), datetime.datetime(2016, 9, 27, 0, 0), datetime.datetime(2016, 9, 28, 0, 0), datetime.datetime(2016, 9, 29, 0, 0), datetime.datetime(2016, 9, 30, 0, 0), datetime.date

我有如下日期时间和值的列表:

import datetime
x = [datetime.datetime(2016, 9, 26, 0, 0), datetime.datetime(2016, 9, 27, 0, 0), 
     datetime.datetime(2016, 9, 28, 0, 0), datetime.datetime(2016, 9, 29, 0, 0),
     datetime.datetime(2016, 9, 30, 0, 0), datetime.datetime(2016, 10, 1, 0, 0)]
y = [26060, 23243, 22834, 22541, 22441, 23248]
import matplotlib.pyplot as plt
plt.plot(x, y)
可以这样画它们:

import datetime
x = [datetime.datetime(2016, 9, 26, 0, 0), datetime.datetime(2016, 9, 27, 0, 0), 
     datetime.datetime(2016, 9, 28, 0, 0), datetime.datetime(2016, 9, 29, 0, 0),
     datetime.datetime(2016, 9, 30, 0, 0), datetime.datetime(2016, 10, 1, 0, 0)]
y = [26060, 23243, 22834, 22541, 22441, 23248]
import matplotlib.pyplot as plt
plt.plot(x, y)
我想能够绘制一个平滑的版本使用更多的x点。首先我要做的是:

delta_t = max(x) - min(x)
N_points = 300
xnew = [min(x) + i*delta_t/N_points for i in range(N_points)]
然后尝试使用scipy进行样条曲线拟合:

from scipy.interpolate import spline
ynew = spline(x, y, xnew)
TypeError:无法根据规则“safe”将数组数据从dtype('O')强制转换为dtype('float64')


最好的方法是什么?我对涉及其他库(如pandas或plotly)的解决方案持开放态度。

您试图将日期时间列表传递给样条函数,这些函数是Python对象(因此
dtype('O')
)。您需要首先将日期时间转换为数字格式,然后根据需要将其转换回:

int_x = [i.total_seconds() for i in x]
ynew = spline(int_x, y, xnew)

编辑:total_seconds()实际上是一个timedelta方法,不适用于datetimes。但是,看起来您已经把它整理好了,所以我将保留这个答案。

您试图将日期时间列表传递给样条函数,这是Python对象(因此
dtype('O')
)。您需要首先将日期时间转换为数字格式,然后根据需要将其转换回:

int_x = [i.total_seconds() for i in x]
ynew = spline(int_x, y, xnew)
编辑:total_seconds()实际上是一个timedelta方法,不适用于datetimes。不过,看起来您已经解决了问题,所以我将保留此答案。

解决了一些问题:

x_ts = [x_.timestamp() for x_ in x]
xnew_ts = [x_.timestamp() for x_ in xnew]

ynew = spline(x_ts, y, xnew_ts)
plt.plot(xnew, ynew)
这非常有效,但我仍然愿意接受更简单方法的想法。

想出了一些办法:

x_ts = [x_.timestamp() for x_ in x]
xnew_ts = [x_.timestamp() for x_ in xnew]

ynew = spline(x_ts, y, xnew_ts)
plt.plot(xnew, ynew)

这非常有效,但我仍然愿意接受更简单方法的想法。

看看
np.datetime64
;它将日期表示为浮点数。您好@AlexG,在使用
.timestamp()
将日期时间转换为数字后,如何将该数字转换回日期时间?@YQ.Wang try datetime.fromTimestamp查看
np.datetime64
;它将日期表示为浮点数。您好@AlexG,在使用
.timestamp()
将日期时间转换为数字后,如何将该数字转换回日期时间?@YQ.Wang请尝试datetime.fromtimestamp