matplotlib datetime.datetime和float错误

时间:2015-11-25 22:30:42

标签: datetime matplotlib

这是打印以下散点图时间/ usd,然后通过

运行最佳拟合3次多项式
from datetime import datetime
from numpy import *
import numpy as np
from matplotlib.pyplot import *
import matplotlib.pyplot as plt


dateStimeSList = [datetime(2015, 11, 24, 14, 27, 47), datetime(2015, 11, 24, 14, 57, 21), datetime(2015, 11, 24, 12, 4, 26), datetime(2015, 11, 24, 12, 4, 11), datetime(2015, 11, 24, 12, 3, 41), datetime(2015, 11, 24, 12, 7, 51), datetime(2015, 11, 24, 12, 7, 48), datetime(2015, 11, 23, 10, 54, 31), datetime(2015, 11, 24, 12, 3, 38), datetime(2015, 11, 23, 10, 58, 58), datetime(2015, 11, 23, 10, 58, 54), datetime(2015, 11, 23, 10, 58, 50), datetime.datetime(2015, 11, 23, 10, 58, 46), datetime(2015, 11, 23, 10, 58, 42), datetime(2015, 11, 21, 7, 56, 1), datetime(2015, 11, 19, 16, 46, 25), datetime(2015, 11, 17, 15, 51, 21)]

priceList = [23.5, 23.0, 22.0, 21.0, 16.0, 13.0, 12.0, 11.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 1.0, 0.99]

plt.plot(dateStimeSList, priceList,'ro')

coefficients = np.polyfit(dateStimeSList, priceList, 3)
polynomial = poly1d(coefficients)
ys = polynomial(priceList)
plot(dateStimeSList, ys)

plt.ylabel('USD')
plt.xlabel('Date/Time')

plt.show()

运行错误

Traceback (most recent call last):
  File "C:/Python34/---/Tv0.0.py", line 50, in <module>
    coefficients = np.polyfit(d, priceList, 3)
  File "C:\Python34\lib\site-packages\numpy\lib\polynomial.py", line 543, in polyfit
    x = NX.asarray(x) + 0.0
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'

这里发生了什么?

1 个答案:

答案 0 :(得分:0)

最不优雅的解决方案

tList = []
t = 0
while t < len(dateStimeSList):
    ti = int(time.mktime(dateStimeSList[t].timetuple()))
    tList.append(ti)
    t = t + 1

plt.plot(tList, priceList,'ro')

z = np.polyfit(tList, priceList, 15)
f = np.poly1d(z)
print(f)
x_new = np.linspace(tList[0], tList[-1], 50)
y_new = f(x_new)
plt.plot(tList,priceList,'o', x_new, y_new)

plt.ylabel('USD')
plt.xlabel('Date/Time')

plt.show()