Skip to content

Commit 78c1611

Browse files
Handle timedelta xoffsets
1 parent fec74b7 commit 78c1611

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

labellines/core.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
import warnings
22
from typing import Optional, Union
3-
3+
from datetime import timedelta
44
import matplotlib.pyplot as plt
55
import numpy as np
66
from matplotlib.container import ErrorbarContainer
7-
from matplotlib.dates import DateConverter, num2date
7+
from matplotlib.dates import (
8+
_SwitchableDateConverter,
9+
ConciseDateConverter,
10+
DateConverter,
11+
num2date,
12+
)
813
from matplotlib.lines import Line2D
914
from more_itertools import always_iterable
1015

@@ -256,15 +261,19 @@ def labelLines(
256261
converter = ax.xaxis.converter
257262
else:
258263
converter = ax.xaxis.get_converter()
259-
if isinstance(converter, DateConverter):
264+
time_classes = (_SwitchableDateConverter, DateConverter, ConciseDateConverter)
265+
if isinstance(converter, time_classes):
260266
xvals = [
261267
num2date(x).replace(tzinfo=ax.xaxis.get_units())
262268
for x in xvals # type: ignore
263269
]
264270

265271
txts = []
266272
try:
267-
xoffsets = [float(xoffsets)] * len(all_lines) # type: ignore
273+
if isinstance(xoffsets, timedelta):
274+
xoffsets = [xoffsets] * len(all_lines) # type: ignore
275+
else:
276+
xoffsets = [float(xoffsets)] * len(all_lines) # type: ignore
268277
except TypeError:
269278
pass
270279
try:

labellines/line_label.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
from typing import TYPE_CHECKING
44

5+
import matplotlib.dates as mdates
56
import matplotlib.patheffects as patheffects
67
import numpy as np
8+
from datetime import timedelta
79
from matplotlib.text import Text
810

911
from .utils import normalize_xydata
@@ -177,6 +179,13 @@ def _update_anchors(self):
177179
x = self._line.convert_xunits(self._target_x)
178180
xdata, ydata = normalize_xydata(self._line)
179181

182+
# Convert timedelta to float if needed
183+
if isinstance(self._xoffset, timedelta):
184+
xoffset = mdates.date2num(self._xoffset + self._target_x) - x
185+
else:
186+
xoffset = self._xoffset
187+
188+
# Handle nan values
180189
mask = np.isfinite(ydata)
181190
if mask.sum() == 0:
182191
raise ValueError(f"The line {self._line} only contains nan!")
@@ -202,9 +211,9 @@ def _update_anchors(self):
202211

203212
# Apply x offset
204213
if self._xoffset_logspace:
205-
x *= 10**self._xoffset
214+
x *= 10**xoffset
206215
else:
207-
x += self._xoffset
216+
x += xoffset
208217

209218
# Apply y offset
210219
if self._yoffset_logspace:

0 commit comments

Comments
 (0)