Plotting dates with sharex=True leads to ValueError: ordinal must be >= 1


Question

When doing some analysis, I stumbled upon a ValueError and I could boil it down to the following simple example which can reproduce the error I got:

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])

When trying to plot this simple x and y array, I have no problems with:

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

or

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

but when adding sharex=True, I get an error:

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

The error message:

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

I found an issue from matplotlib (https://github.com/matplotlib/matplotlib/issues/162) about the use of twinx with dates giving the same error. Is it the same bug? And it seems a long known bug, but not yet solved.

1
13
11/24/2012 9:14:34 AM

Accepted Answer

The error is avoided if you plot something on the second axis:

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()
16
11/24/2012 10:33:30 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon