Skip to content

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

Closed
@scottshambaugh

Description

@scottshambaugh

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions