如何修复 matplotlib axvline() TypeError: '<' not supported between instances of 'Timedelta' and 'numpy.float64'

问题:

在向具有 timedelta X 轴的 matplotlib 图添加 axvline 时,你收到以下错误:

axvline_timedelta_fix.py
--> 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'

解决方案

目前,axvline 不支持直接传递 Timedelta 对象。

相反,你需要将其作为纳秒为单位的 float 传递。

如果你想传递 pandaspd.Timedelta 对象,可以这样将其转换为纳秒:

axvline_timedelta_solution.py
import pandas as pd

xpos = pd.Timedelta('1 days')

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

Check out similar posts by category: Python, MatPlotLib