How can I display error bars an a datetime.datetime axis?

Question:

I’m trying to make a plot with error bars along the time axis, ideally with adjustable upper/lower error limits. I’ve been using the datetime.datetime datatype to do this, which has been reliable until I’ve tried to implement error bars with matplotlib.pyplot.errorbar().

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

dates = [datetime(1950,2,2,12),datetime(1950,2,2,15)]
data = [1,2]
date_err = [[datetime(1950,2,2,11,30),datetime(1950,2,2,14,30)], #arbitrary random dates/times
            [datetime(1950,2,2,12,30),datetime(1950,2,2,15,30)]]
test_err = [2,3]
fig, (ax1,ax2) = plt.subplots(2,1)
ax1.plot(dates,data,'k.')
ax1.tick_params(rotation = 45)
plt.subplots_adjust(hspace = 0.5)
ax2.errorbar(dates,data,xerr = test_err) #I tried both with date_err and test_err
ax2.errorbar(dates,data,xerr = date_err)

which gives the plot:

enter image description here

I tried both using a list shape (2,N) with format [[low1,low2…lowN],[high1,high2…highN]] with datatype datetime.datetime() but I recieve the error:

TypeError: unsupported operand type(s) for *: ‘int’ and ‘datetime.datetime’

When using integers/floating point numbers like in test_err, I get the error:

TypeError: unsupported operand type(s) for +: ‘datetime.datetime’ and ‘int’

Can anyone either suggest an alternative way to plot with dates/times or a way to implement error bars along the temporal axis? Thank you!

Asked By: JBowers

||

Answers:

I’m guessing you want timedelta:

from datetime import datetime, timedelta

test_err = [timedelta(hours=2), timedelta(hours=3)]
ax2.errorbar(dates, data, xerr=test_err)

Output:

enter image description here

Answered By: BigBen

You can use timedelta as the errors. I don’t know what your desired errors are, but you can easily adjust that.

import matplotlib.pyplot as plt
from datetime import datetime, timedelta

plt.close("all")

dates = [datetime(1950, 2, 2, 12), datetime(1950, 2, 2, 15)]
data = [1, 2]
test_err = [timedelta(minutes=30), timedelta(hours=2)]

fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.plot(dates, data, 'k.')
ax2.errorbar(dates, data, xerr=test_err, capsize=3)
ax1.tick_params(rotation=45)
ax2.tick_params(rotation=45)
fig.tight_layout()
fig.show()

enter image description here

Answered By: jared