How to fix matplotlib axvline() TypeError: '<' not supported between instances of 'Timedelta' and 'numpy.float64'

Problem:

When adding an axvline to a matplotlib plot with a timedelta X-axis, you get the following error:

--> 147 ax1.axvline(xpos, color='black', linestyle='-')

File /usr/local/lib/python3.10/dist-packages/matplotlib/axes/_axes.py:893, in Axes.axvline(self, x, ymin, ymax, **kwargs)
    891 # Strip away the units for comparison with non-unitized bounds.
    892 xx, = self._process_unit_info([("x", x)], kwargs)
--> 893 scalex = (xx < xmin) or (xx > xmax)
    895 trans = self.get_xaxis_transform(which='grid')
    896 l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)

TypeError: '<' not supported between instances of 'Timedelta' and 'numpy.float64'

Solution:

Currently, axvline does not support passing Timedelta objects directly.

Instead, you need to pass it as a float in nanoseconds.

If you want to pass a pandas pd.Timedelta object, you can convert it to nanoseconds like this:

import pandas as pd

xpos = pd.Timedelta('1 days')

ax.axvline(xpos.total_seconds()*1e9, color='black', linestyle='-')