Skip to content

Cannot use a timedelta Rectangle width with a datetime axis #4916

@brandon-rhodes

Description

@brandon-rhodes

I would like to draw a rectangle to represent the weekend on a plot whose x-axis is time. In an IPython Notebook:

%pylab inline
dt = datetime.datetime
dates = [
    dt(2015, 1, 1),
    dt(2015, 1, 2),
    dt(2015, 1, 3),
    dt(2015, 1, 4),
    dt(2015, 1, 5),
    ]
data = [56.0, 53.2, 57.8, 59.1, 55.5]
gca().add_patch(Rectangle(
    xy=(dt(2015, 1, 3), 50.0),
    width=datetime.timedelta(days=2), 
    height=1.0,
    ))
plot(dates, data)

The big problem is that the above code dies with an exception.

AttributeError                            Traceback (most recent call last)
<ipython-input-13-b4545adc3ff2> in <module>()
     12     xy=(dt(2015, 1, 3), 50.0),
     13     width=datetime.timedelta(days=2),
---> 14     height=1.0,
     15     ))
     16 plot(dates, data)

...

/home/brhodes/.v/misc/lib/python2.7/site-packages/matplotlib/dates.pyc in _to_ordinalf(dt)
    202             dt -= delta
    203 
--> 204     base = float(dt.toordinal())
    205     if hasattr(dt, 'hour'):
    206         base += (dt.hour / HOURS_PER_DAY + dt.minute / MINUTES_PER_DAY +

AttributeError: 'datetime.timedelta' object has no attribute 'toordinal'

The other problem is that my backup plan, of replacing the timedelta() with the floating-point value 2.0, destroys the date-ness of the x axis. It reverts to being a float that does not display as a date.

Why is a timedelta not a valid increment or offset with which I can express width along a datetime x-axis?

Thanks for any help you can provide!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions