在matplotlib中绘制datetime对象

时间:2014-10-10 18:43:04

标签: python datetime matplotlib

我有一个日期时间对象数组,如下所示

dates = [datetime.datetime(1900, 1, 1, 10, 8, 14, 565000), datetime.datetime(1900, 1, 1, 10, 8, 35, 330000), datetime.datetime(1900, 1, 1, 10, 8, 43, 358000), datetime.datetime(1900, 1, 1, 10, 8, 52, 808000)]

然后我尝试使用dates = plt.dates.date2num(dates)

将数组转换为matplotlib合适的对象

然后我尝试使用ax1.plot_date(dates, datac)

对某些值进行绘制

但收到的错误如下:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:\Python34\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 278, in resize
    self.show()
  File "C:\Python34\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 349, in draw
    FigureCanvasAgg.draw(self)
  File "C:\Python34\lib\site-packages\matplotlib\backends\backend_agg.py", line 461, in draw
    self.figure.draw(self.renderer)
  File "C:\Python34\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python34\lib\site-packages\matplotlib\figure.py", line 1079, in draw
    func(*args)
  File "C:\Python34\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python34\lib\site-packages\matplotlib\axes\_base.py", line 2092, in draw
    a.draw(renderer)
  File "C:\Python34\lib\site-packages\matplotlib\artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python34\lib\site-packages\matplotlib\axis.py", line 1103, in draw
    ticks_to_draw = self._update_ticks(renderer)
  File "C:\Python34\lib\site-packages\matplotlib\axis.py", line 957, in _update_ticks
    tick_tups = [t for t in self.iter_ticks()]
  File "C:\Python34\lib\site-packages\matplotlib\axis.py", line 957, in <listcomp>
    tick_tups = [t for t in self.iter_ticks()]
  File "C:\Python34\lib\site-packages\matplotlib\axis.py", line 905, in iter_ticks
    for i, val in enumerate(majorLocs)]
  File "C:\Python34\lib\site-packages\matplotlib\axis.py", line 905, in <listcomp>
    for i, val in enumerate(majorLocs)]
  File "C:\Python34\lib\site-packages\matplotlib\dates.py", line 580, in __call__
    result = self._formatter(x, pos)
  File "C:\Python34\lib\site-packages\matplotlib\dates.py", line 412, in __call__
    return self.strftime(dt, self.fmt)
  File "C:\Python34\lib\site-packages\matplotlib\dates.py", line 450, in strftime
    s1 = time.strftime(fmt, (year,) + timetuple[1:])
ValueError: Invalid format string

有没有人对如何解决此问题有任何建议?提前谢谢!

1 个答案:

答案 0 :(得分:1)

dates = plt.dates.date2num(dates)

不适合您使用以下命令

import matplotlib.pyplot as plt

所以这里的plt不包含date2num函数。所以你必须使用

from matplotlib.dates import date2num

dates =date2num(dates)。 我认为这样可以正常工作