3
3
from datetime import timedelta
4
4
import matplotlib .pyplot as plt
5
5
import numpy as np
6
+ from datetime import datetime
6
7
from matplotlib .container import ErrorbarContainer
7
8
from matplotlib .dates import (
8
9
_SwitchableDateConverter ,
@@ -204,18 +205,34 @@ def labelLines(
204
205
if isinstance (xvals , tuple ) and len (xvals ) == 2 :
205
206
xmin , xmax = xvals
206
207
xscale = ax .get_xscale ()
208
+
209
+ # Convert datetime objects to numeric values for linspace/geomspace
210
+ x_is_datetime = isinstance (xmin , datetime ) or isinstance (xmax , datetime )
211
+ if x_is_datetime :
212
+ if not isinstance (xmin , datetime ) or not isinstance (xmax , datetime ):
213
+ raise ValueError (
214
+ f"Cannot mix datetime and numeric values in xvals: { xvals } "
215
+ )
216
+ xmin = plt .matplotlib .dates .date2num (xmin )
217
+ xmax = plt .matplotlib .dates .date2num (xmax )
218
+
207
219
if xscale == "log" :
208
220
xvals = np .geomspace (xmin , xmax , len (all_lines ) + 2 )[1 :- 1 ]
209
221
else :
210
222
xvals = np .linspace (xmin , xmax , len (all_lines ) + 2 )[1 :- 1 ]
211
223
224
+ # Convert numeric values back to datetime objects
225
+ if x_is_datetime :
226
+ xvals = plt .matplotlib .dates .num2date (xvals )
227
+
212
228
# Build matrix line -> xvalue
213
229
ok_matrix = np .zeros ((len (all_lines ), len (all_lines )), dtype = bool )
214
230
215
231
for i , line in enumerate (all_lines ):
216
232
xdata , _ = normalize_xydata (line )
217
233
minx , maxx = min (xdata ), max (xdata )
218
234
for j , xv in enumerate (xvals ): # type: ignore
235
+ xv = line .convert_xunits (xv )
219
236
ok_matrix [i , j ] = minx < xv < maxx
220
237
221
238
# If some xvals do not fall in their corresponding line,
@@ -242,6 +259,8 @@ def labelLines(
242
259
# Move xlabel if it is outside valid range
243
260
xdata , _ = normalize_xydata (line )
244
261
xmin , xmax = min (xdata ), max (xdata )
262
+ xv = line .convert_xunits (xv )
263
+
245
264
if not (xmin <= xv <= xmax ):
246
265
warnings .warn (
247
266
(
0 commit comments