python plot stem with datetime base

时间:2013-11-05 16:44:25

标签: python matplotlib

我希望使用datetime base绘制带有matplotlib的词干。但似乎错误发生了: 示例代码:

import matplotlib.pyplot as plt
from dateutil import parser

x = parser.parse("2013-9-28 11:00:00")
y = 100

x1 = parser.parse("2013-9-28 12:00:00")
y1 = 200

plt.stem([x,x1],[y,y1],"*-")

错误消息:

    318 
    319     """
--> 320     return array(a, dtype, copy=False, order=order)
    321 
    322 def asanyarray(a, dtype=None, order=None):

TypeError: float() argument must be a string or a number

1 个答案:

答案 0 :(得分:1)

似乎干x轴只允许浮动,因此您可以将日期转换为时间戳(浮点)然后绘制。要在轴上显示日期,请使用.xticks()。这是一个例子:

import numpy as np
import matplotlib.pyplot as plt
from time import mktime
from datetime import datetime

ticks = [ "2013-9-28 11:00:00.234", "2013-9-28 11:10:00.123", "2013-9-28 11:40:00.654", "2013-9-28 11:50:00.341", "2013-9-28 12:00:00.773"]
y = np.array([10, 12, 9, 15, 11])
x = [mktime(datetime.strptime(i, "%Y-%m-%d %H:%M:%S.%f").timetuple()) for i in ticks]

plt.stem(x,y)
plt.xticks(x, ticks)
plt.show()

enter image description here