使用sharex = True绘制日期会导致ValueError:ordinal必须为> = 1

时间:2012-11-24 09:14:34

标签: python numpy matplotlib

在做一些分析时,我偶然发现了一个ValueError,我可以将它归结为以下简单示例,它可以重现我得到的错误:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0),
              dt.datetime(2012, 10, 19, 10, 0, 1),
              dt.datetime(2012, 10, 19, 10, 0, 2),
              dt.datetime(2012, 10, 19, 10, 0, 3)])

y = np.array([1, 3, 4, 2])

当试图绘制这个简单的x和y数组时,我没有遇到任何问题:

fig, ax = plt.subplots()
ax.plot(x, y)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(x, y)

但是在添加sharex=True时,我收到错误:

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
ax1.plot(x, y)

错误消息:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2445, in home
    self._update_view()
  File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2818, in _update_view
    self.draw()
  File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2796, in draw
    loc.refresh()
  File "C:\Python27\lib\site-packages\matplotlib\dates.py", line 758, in refresh
    dmin, dmax = self.viewlim_to_dt()
  File "C:\Python27\lib\site-packages\matplotlib\dates.py", line 530, in viewlim_to_dt
    return num2date(vmin, self.tz), num2date(vmax, self.tz)
  File "C:\Python27\lib\site-packages\matplotlib\dates.py", line 289, in num2date
    if not cbook.iterable(x): return _from_ordinalf(x, tz)
  File "C:\Python27\lib\site-packages\matplotlib\dates.py", line 203, in _from_ordinalf
    dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1

我在matplotlib(https://github.com/matplotlib/matplotlib/issues/162)中发现了一个问题,即twinx使用日期给出相同的错误。它是同一个bug吗?它似乎是一个众所周知的错误,但尚未解决。

1 个答案:

答案 0 :(得分:16)

如果您在第二轴上绘制某些内容,则可以避免错误:

import matplotlib.pyplot as plt
import numpy as np
import datetime as dt

x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0),
              dt.datetime(2012, 10, 19, 10, 0, 1),
              dt.datetime(2012, 10, 19, 10, 0, 2),
              dt.datetime(2012, 10, 19, 10, 0, 3)])

y = np.array([1, 3, 4, 2])

fig, (ax1, ax2) = plt.subplots(nrows = 2, sharex = True)
ax1.plot(x, y, 'b-')
ax2.plot(x, 1.0/y, 'r-')
plt.show()