Wie man matplotlib axvline() TypeError behebt: '<' not supported between instances of 'Timedelta' and 'numpy.float64'
Problem:
Beim Hinzufügen einer axvline zu einem matplotlib-Plot mit einer Timedelta-X-Achse erhalten Sie den folgenden Fehler:
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'Lösung
Derzeit unterstützt axvline nicht das direkte Übergeben von Timedelta-Objekten.
Stattdessen müssen Sie es als float in Nanosekunden übergeben.
Wenn Sie ein pandas-pd.Timedelta-Objekt übergeben möchten, können Sie es wie folgt in Nanosekunden umwandeln:
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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow