matplotlib-label-lines icon indicating copy to clipboard operation
matplotlib-label-lines copied to clipboard

Error with `xvals` argument on a time axis with Timestamp or datetime values

Open scottshambaugh opened this issue 9 months ago • 2 comments

If I try to use the xvals argument by supplying time information on a time axis, I get errors. This happens with both a pandas Timestamps and datetime64 objects. Adding labels in both cases without specifying the xvals is working just fine.

Example with pandas:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from labellines import labelLines

x = np.linspace(0, 10, 100)
t = pd.date_range(start='2020-01-01', periods=100)  # Creates a DatetimeIndex
df = pd.DataFrame({'x': x, 't': t})

fig, ax = plt.subplots()

ax.plot(df['t'], df['x'], label='x')
labelLines(ax.get_lines(), zorder=2.5, xvals=df['t'].iloc[0])  # df['t'].iloc[0] is a pandas Timestamp

plt.show()

Results in this error:

Exception has occurred: TypeError
'<=' not supported between instances of 'numpy.float64' and 'Timestamp'
  File "/home/scott/coding/_test.py", line 13, in <module>
    labelLines(ax.get_lines(), zorder=2.5, xvals=df['t'][0])
TypeError: '<=' not supported between instances of 'numpy.float64' and 'Timestamp'

And then this substitution to show datetimes:

datetimes = pd.to_datetime(df['t']).values  # Creates a numpy array with dtype np.datetime64
ax.plot(datetimes, df['x'], label='x')
labelLines(ax.get_lines(), zorder=2.5, xvals=datetimes[0])

Results in this error:

ufunc 'less_equal' did not contain a loop with signature matching types (<class 'numpy.dtypes.Float64DType'>, <class 'numpy.dtypes.DateTime64DType'>) -> None
  File "/home/scott/coding/_test.py", line 15, in <module>
    labelLines(ax.get_lines(), zorder=2.5, xvals=datetimes[0])
numpy._core._exceptions._UFuncNoLoopError: ufunc 'less_equal' did not contain a loop with signature matching types (<class 'numpy.dtypes.Float64DType'>, <class 'numpy.dtypes.DateTime64DType'>) -> None

scottshambaugh avatar Mar 06 '25 03:03 scottshambaugh

Thanks for the report. This is indeed a bug. Did you manage to fix it manually? I never work with timestamps myself.

cphyc avatar Mar 07 '25 09:03 cphyc

Sure did, and PR opened for a fix!

scottshambaugh avatar Mar 07 '25 14:03 scottshambaugh