mintfig 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. mintfig/__init__.py +162 -0
  2. mintfig/_explain/__init__.py +1 -0
  3. mintfig/_explain/change.py +392 -0
  4. mintfig/_explain/compare.py +1308 -0
  5. mintfig/_explain/compare_grouped.py +472 -0
  6. mintfig/_explain/core.py +2005 -0
  7. mintfig/_explain/distribution.py +1268 -0
  8. mintfig/_explain/flow.py +508 -0
  9. mintfig/_explain/layout.py +2012 -0
  10. mintfig/_explain/matrix.py +623 -0
  11. mintfig/_explain/relate.py +1318 -0
  12. mintfig/_explain/timeline.py +595 -0
  13. mintfig/_explain/trend.py +2557 -0
  14. mintfig/_explain/waterfall.py +459 -0
  15. mintfig/_table.py +691 -0
  16. mintfig/_tabular.py +738 -0
  17. mintfig/annotations.py +1165 -0
  18. mintfig/assets/AGENTS_SNIPPET.md +11 -0
  19. mintfig/assets/SKILL.md +143 -0
  20. mintfig/assets/__init__.py +1 -0
  21. mintfig/assets/references/publication.md +79 -0
  22. mintfig/assets/references/scientific_and_recipes.md +213 -0
  23. mintfig/audit.py +179 -0
  24. mintfig/brief.py +518 -0
  25. mintfig/bundle.py +333 -0
  26. mintfig/cli.py +1300 -0
  27. mintfig/edit.py +347 -0
  28. mintfig/epistemic.py +1083 -0
  29. mintfig/explainer.py +194 -0
  30. mintfig/export.py +247 -0
  31. mintfig/inspect_data.py +583 -0
  32. mintfig/interactive.py +1028 -0
  33. mintfig/palettes.py +233 -0
  34. mintfig/plate.py +784 -0
  35. mintfig/preflight.py +2398 -0
  36. mintfig/proof.py +627 -0
  37. mintfig/runner.py +403 -0
  38. mintfig/skill.py +167 -0
  39. mintfig/specs.py +291 -0
  40. mintfig/style.py +151 -0
  41. mintfig/terminal.py +785 -0
  42. mintfig/themes.py +660 -0
  43. mintfig-0.2.0.dist-info/METADATA +239 -0
  44. mintfig-0.2.0.dist-info/RECORD +47 -0
  45. mintfig-0.2.0.dist-info/WHEEL +4 -0
  46. mintfig-0.2.0.dist-info/entry_points.txt +2 -0
  47. mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2557 @@
1
+ """trend() form for mint.explain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import math
7
+ from collections.abc import Callable, Collection, Mapping, Sequence
8
+ from datetime import date, datetime
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ from matplotlib import dates as mdates
13
+ from matplotlib.axes import Axes
14
+ from matplotlib.ticker import (
15
+ FixedLocator,
16
+ FuncFormatter,
17
+ MaxNLocator,
18
+ NullFormatter,
19
+ )
20
+ from matplotlib.transforms import Bbox
21
+
22
+ from ..annotations import _relax_positions_pt
23
+ from ..themes import (
24
+ MINTFIG_THEME,
25
+ Theme,
26
+ )
27
+ from .core import (
28
+ _ISO_DATE,
29
+ _SCI_LARGE_PHYSICAL,
30
+ MAX_COLORED_SERIES,
31
+ MAX_FACETS,
32
+ MAX_HIGHLIGHTS,
33
+ ExplainError,
34
+ Panel,
35
+ _and_list,
36
+ _apply_inline_y_ticks,
37
+ _base_spec,
38
+ _baseline_name,
39
+ _change_text,
40
+ _clear_inline_ticks,
41
+ _Ctx,
42
+ _data_paths,
43
+ _date_formatter,
44
+ _diff_with_unit,
45
+ _formatter,
46
+ _guarded,
47
+ _halfwidth,
48
+ _has_items,
49
+ _interval_issue,
50
+ _interval_mode_text,
51
+ _is_number,
52
+ _is_one_dimensional,
53
+ _is_strict,
54
+ _issue,
55
+ _jsonable,
56
+ _Measure,
57
+ _names,
58
+ _narrow_log_ticks,
59
+ _pairs,
60
+ _plain,
61
+ _ratio_text,
62
+ _record_adjustment,
63
+ _reference_line,
64
+ _relative_text,
65
+ _resolve_x_unit,
66
+ _sig_text,
67
+ _signed,
68
+ _Sizes,
69
+ _slope_ci,
70
+ _tick_label,
71
+ _tick_label_boxes,
72
+ _to_float,
73
+ _unsigned,
74
+ _value_axis,
75
+ _values_array,
76
+ _vs_text,
77
+ _with_unit,
78
+ )
79
+
80
+ # --------------------------------------------------------------------------- #
81
+ # trend
82
+ # --------------------------------------------------------------------------- #
83
+
84
+
85
+ def _parse_x(x: Sequence[Any]) -> tuple[str, np.ndarray, list[str]]:
86
+ """Return ``(kind, positions, display strings)`` for numeric, date or ordered-category x."""
87
+ if x is None or isinstance(x, (str, bytes)) or _is_number(x):
88
+ raise ExplainError(
89
+ f"trend(x) must be a list of x positions, got {type(x).__name__}.",
90
+ fix_hint="Pass numbers, dates (ISO strings or date objects) or ordered labels, one "
91
+ "per value of each series.",
92
+ )
93
+ xs = list(x)
94
+ if len(xs) < 2:
95
+ raise ExplainError(
96
+ "trend() needs at least two x positions.",
97
+ fix_hint="Use compare() for a single point in time.",
98
+ )
99
+ if all(_is_number(v) for v in xs):
100
+ arr = np.asarray([float(v) for v in xs], dtype=float)
101
+ if not np.all(np.isfinite(arr)):
102
+ raise ExplainError(
103
+ "trend(x) contains a missing or infinite x value.",
104
+ fix_hint="Drop the positions with no x (and their series values) first.",
105
+ )
106
+ return "number", arr, [_x_text(v) for v in arr]
107
+ if all(isinstance(v, (datetime, date, np.datetime64)) for v in xs) or all(
108
+ isinstance(v, str) and _ISO_DATE.match(v) for v in xs
109
+ ):
110
+ try:
111
+ stamps = np.array([np.datetime64(v) for v in xs], dtype="datetime64[s]")
112
+ except ValueError as exc:
113
+ raise ExplainError(
114
+ f"trend(x) dates could not be read ({exc}).",
115
+ fix_hint="Pass ISO dates such as '2026-01-31' or date/datetime objects.",
116
+ ) from exc
117
+ days = stamps.astype("datetime64[D]")
118
+ if np.all(stamps == days):
119
+ shown = [str(v)[:10] for v in xs]
120
+ else: # sub-day data: a fact reading "from 2026-01-01 to 2026-01-01" says nothing
121
+ shown = [str(v).replace("T", " ")[:16] for v in stamps]
122
+ return "date", np.asarray(mdates.date2num(stamps), dtype=float), shown
123
+ return "category", np.arange(len(xs), dtype=float), [str(v) for v in xs]
124
+
125
+
126
+ def _with_x_unit(text: str, x_unit: str | None) -> str:
127
+ """An x value with its unit for facts ("19 h", "40%"); unchanged without one."""
128
+ if not x_unit:
129
+ return text
130
+ return f"{text}{x_unit}" if x_unit.startswith("%") else f"{text} {x_unit}"
131
+
132
+
133
+ def _x_text(v: float) -> str:
134
+ """An x value in facts: years plain, others to three significant figures ("3.03")."""
135
+ if v == round(v) and 1000 <= v <= 2200:
136
+ return f"{v:.0f}"
137
+ return _sig_text(float(v), large=_SCI_LARGE_PHYSICAL)
138
+
139
+
140
+ def _series_map(series: object, n: int) -> tuple[dict[str, np.ndarray], bool]:
141
+ """``({name: values}, single)``; a mapping, a pandas DataFrame, or one bare sequence."""
142
+ if series is None:
143
+ return {}, False
144
+ from .._tabular import is_row_records
145
+
146
+ if is_row_records(series):
147
+ cols = list(dict.fromkeys(str(k) for row in series for k in row)) # type: ignore[union-attr]
148
+ shown = ", ".join(repr(c) for c in cols[:8])
149
+ raise ExplainError(
150
+ f"trend(series) received row-shaped dicts (columns: {shown}) instead of wide series.",
151
+ fix_hint=(
152
+ 'Pass tidy rows via data=: mint.trend("x_col", "series_col", y="y_col", data=rows), '
153
+ 'or pivot wide first (e.g. df.pivot(index="x", columns="series", values="y")).'
154
+ ),
155
+ )
156
+ if _has_items(series) and not _is_one_dimensional(series):
157
+ raw = {str(k): v for k, v in _pairs(series)}
158
+ single = False
159
+ else:
160
+ raw = {"": series}
161
+ single = True
162
+ out: dict[str, np.ndarray] = {}
163
+ for name, values in raw.items():
164
+ arr = _values_array(values, f"trend(series[{name!r}])")
165
+ if arr.ndim != 1 or arr.size != n:
166
+ raise ExplainError(
167
+ f"trend(series[{name!r}]) has {arr.size} values but x has {n}.",
168
+ fix_hint="Every series must have one value per x position (None for gaps).",
169
+ )
170
+ out[name] = arr
171
+ if not out:
172
+ raise ExplainError("trend(series) is empty.", fix_hint="Pass at least one series.")
173
+ return out, single
174
+
175
+
176
+ def _replicates(points: object, n: int, names_hint: Sequence[str]) -> dict[str, list[np.ndarray]]:
177
+ """Read ``trend(points=...)``: per series, the raw replicate values at each x."""
178
+ hint = (
179
+ 'Pass points={"name": [[replicates at x0], [replicates at x1], ...]} or '
180
+ "{name: 2-D array of shape (n_x, n_replicates)}; use NaN or an empty list where an x "
181
+ "has no measurement."
182
+ )
183
+ if _has_items(points) and not _is_one_dimensional(points):
184
+ raw = {str(k): v for k, v in _pairs(points)}
185
+ elif len(names_hint) <= 1:
186
+ raw = {names_hint[0] if names_hint else "": points}
187
+ else:
188
+ raise ExplainError("trend(points) must map series names to replicates.", fix_hint=hint)
189
+ out: dict[str, list[np.ndarray]] = {}
190
+ for name, rows in raw.items():
191
+ if isinstance(rows, (str, bytes)) or _is_number(rows) or rows is None:
192
+ raise ExplainError(
193
+ f"trend(points[{name!r}]) is not a list of replicates.", fix_hint=hint
194
+ )
195
+ rows_list = list(rows) # type: ignore[call-overload]
196
+ if len(rows_list) != n:
197
+ raise ExplainError(
198
+ f"trend(points[{name!r}]) has {len(rows_list)} rows but x has {n}.",
199
+ fix_hint=hint,
200
+ )
201
+ per_x: list[np.ndarray] = []
202
+ for row in rows_list:
203
+ if row is None or _is_number(row):
204
+ arr = np.asarray([np.nan if row is None else float(row)], dtype=float)
205
+ else:
206
+ arr = _values_array(row, f"trend(points[{name!r}])")
207
+ per_x.append(arr[np.isfinite(arr)])
208
+ out[name] = per_x
209
+ return out
210
+
211
+
212
+ def _trend_bands(
213
+ band: object, data: dict[str, np.ndarray], n: int
214
+ ) -> tuple[dict[str, tuple[np.ndarray, np.ndarray]], dict[str, Any], set[str]]:
215
+ """Read ``trend(band=...)``: per series (low, high) sequences, half-width sequence or number.
216
+
217
+ Returns the absolute bounds, the per-series normalised spec, and the modes read.
218
+ """
219
+ hint = (
220
+ "Per series pass (low_values, high_values) as absolute bounds, one half-width per x, "
221
+ 'or one number for a constant \N{PLUS-MINUS SIGN} band, e.g. band={"a": 0.5}.'
222
+ )
223
+ names = list(data)
224
+ if band is None:
225
+ return {}, {}, set()
226
+ if _has_items(band) and not _is_one_dimensional(band):
227
+ raw = {str(k): v for k, v in _pairs(band)}
228
+ elif len(names) == 1:
229
+ raw = {names[0]: band}
230
+ else:
231
+ raise ExplainError(
232
+ "trend(band) must map series names to bands when there are several series.",
233
+ fix_hint=hint,
234
+ )
235
+ bounds: dict[str, tuple[np.ndarray, np.ndarray]] = {}
236
+ spec: dict[str, Any] = {}
237
+ modes: set[str] = set()
238
+ for name, entry in raw.items():
239
+ if name not in data:
240
+ raise ExplainError(
241
+ f"trend(band) names {name!r}, which is not a series.",
242
+ fix_hint=f"Use one of: {', '.join(map(repr, names))}.",
243
+ )
244
+ values = data[name]
245
+ if _is_number(entry):
246
+ hw = _halfwidth(entry, f"trend(band[{name!r}])")
247
+ bounds[name] = (values - hw, values + hw)
248
+ spec[name] = hw
249
+ modes.add("halfwidth")
250
+ continue
251
+ try:
252
+ arr = np.asarray(
253
+ [[np.nan if v is None else float(v) for v in part] for part in entry] # type: ignore[union-attr]
254
+ if not isinstance(entry, np.ndarray)
255
+ else entry,
256
+ dtype=float,
257
+ )
258
+ except (TypeError, ValueError):
259
+ try:
260
+ arr = np.asarray(
261
+ [np.nan if v is None else float(v) for v in entry], # type: ignore[union-attr]
262
+ dtype=float,
263
+ )
264
+ except (TypeError, ValueError) as exc:
265
+ raise ExplainError(f"trend(band[{name!r}]) is not numeric.", fix_hint=hint) from exc
266
+ if arr.ndim == 2 and arr.shape == (2, n):
267
+ low, high = arr[0], arr[1]
268
+ ok = np.isfinite(low) & np.isfinite(high) & np.isfinite(values)
269
+ if np.any(low[ok] > high[ok]) or np.any(
270
+ (values[ok] < low[ok] - 1e-12 * np.abs(values[ok]))
271
+ | (values[ok] > high[ok] + 1e-12 * np.abs(values[ok]))
272
+ ):
273
+ raise ExplainError(
274
+ f"trend(band[{name!r}]) (low, high) does not bracket the series values.",
275
+ fix_hint="Pass absolute (low, high) bounds, not +/- offsets; for a symmetric "
276
+ "band pass the half-widths (one sequence) or one number.",
277
+ )
278
+ bounds[name] = (low, high)
279
+ spec[name] = [low.tolist(), high.tolist()]
280
+ modes.add("bounds")
281
+ elif arr.ndim == 1 and arr.size == n:
282
+ if np.any(arr[np.isfinite(arr)] < 0):
283
+ raise ExplainError(
284
+ f"trend(band[{name!r}]) has a negative half-width.", fix_hint=hint
285
+ )
286
+ bounds[name] = (values - arr, values + arr)
287
+ spec[name] = arr.tolist()
288
+ modes.add("halfwidth")
289
+ else:
290
+ raise ExplainError(
291
+ f"trend(band[{name!r}]) has shape {arr.shape}; with {n} x positions expected "
292
+ f"(2, {n}) bounds, {n} half-widths or one number.",
293
+ fix_hint=hint,
294
+ )
295
+ return bounds, spec, modes
296
+
297
+
298
+ def _r2_text(r2: float) -> str:
299
+ """R² to three decimals, four when it would otherwise read as 1.000."""
300
+ return f"{r2:.4f}" if 0.9995 <= r2 < 1.0 else f"{r2:.3f}"
301
+
302
+
303
+ def _log_trend_facts(
304
+ data: Mapping[str, np.ndarray],
305
+ names: Sequence[str],
306
+ xpos: np.ndarray,
307
+ x_kind: str,
308
+ log_x: bool,
309
+ label: str | None,
310
+ x_text: Sequence[str] | None = None,
311
+ x_unit: str | None = None,
312
+ spiked: Collection[str] = (),
313
+ power_names: Sequence[str] | None = None,
314
+ ) -> list[str]:
315
+ """Facts a log-scale trend is judged by: slopes of log₁₀(y) and peak ratios; on
316
+ log-log axes (``log_x``) the power-law exponent of each of ``power_names`` with its
317
+ 95% CI and R².
318
+
319
+ The least-squares slope of log₁₀(y) against x (plotted x units, numeric linear x
320
+ only) with its R² lets an agent check an Arrhenius or exponential claim. A series
321
+ that rises then falls (or falls then rises) is fitted on each side of its interior
322
+ peak (or trough), never across it: one line through a rise and a decay describes
323
+ neither (an absorption phase would hide the elimination rate). When the peak is
324
+ not an endpoint, its ratio to the first and last values (unrounded), except for
325
+ ``spiked`` series, whose event-marked spike is stated against the median before it.
326
+ """
327
+ per = f"per {x_unit}" if x_unit else "per unit x"
328
+ log10 = "log\N{SUBSCRIPT ONE}\N{SUBSCRIPT ZERO}"
329
+
330
+ def _slope_fact(shown: str, sel: np.ndarray, arr: np.ndarray, where: str) -> str | None:
331
+ lx, ly = xpos[sel].astype(float), np.log10(arr[sel])
332
+ if sel.size < 3 or np.ptp(lx) <= 0:
333
+ return None
334
+ slope, icept = np.polyfit(lx, ly, 1)
335
+ resid = ly - (slope * lx + icept)
336
+ total = float(((ly - ly.mean()) ** 2).sum())
337
+ r2 = 1.0 - float((resid**2).sum()) / total if total > 0 else float("nan")
338
+ return (
339
+ f"{shown}: {log10} slope {_sig_text(float(slope), 3)} {per}{where}"
340
+ + (f", R\N{SUPERSCRIPT TWO} = {_r2_text(r2)}" if math.isfinite(r2) else "")
341
+ )
342
+
343
+ def _power_fact(shown: str, sel: np.ndarray, arr: np.ndarray, where: str) -> str | None:
344
+ """Log-log axes: the power-law exponent (slope of log y on log x) with its 95% CI."""
345
+ lx, ly = np.log10(xpos[sel].astype(float)), np.log10(arr[sel])
346
+ if sel.size < 3 or np.ptp(lx) <= 0:
347
+ return None
348
+ slope, icept = np.polyfit(lx, ly, 1)
349
+ resid = ly - (slope * lx + icept)
350
+ total = float(((ly - ly.mean()) ** 2).sum())
351
+ r2 = 1.0 - float((resid**2).sum()) / total if total > 0 else float("nan")
352
+ lo, hi = _slope_ci(lx, ly, float(slope), float(icept))
353
+ ci = ""
354
+ if math.isfinite(lo) and math.isfinite(hi):
355
+ joint = " to " if lo < 0 else "\N{EN DASH}"
356
+ ci = f" (95% CI {_sig_text(lo, 3)}{joint}{_sig_text(hi, 3)})"
357
+ return (
358
+ f"{shown}: y \N{PROPORTIONAL TO} x^{_sig_text(float(slope), 3)}{ci}{where}"
359
+ + (f", R\N{SUPERSCRIPT TWO} = {_r2_text(r2)}" if math.isfinite(r2) else "")
360
+ )
361
+
362
+ out: list[str] = []
363
+ if x_kind == "number" and log_x:
364
+ # A straight line on log-log axes is a power law: its exponent is the claim
365
+ # ("loss falls as compute^−0.063"), checkable only with its interval. Every
366
+ # series (``power_names``, grey ones too): "faster than the others" needs theirs.
367
+ for name in names if power_names is None else power_names:
368
+ arr = data[name]
369
+ ok = np.isfinite(arr) & (arr > 0)
370
+ if ok.sum() >= 3:
371
+ fact = _power_fact(name or (label or "value"), np.flatnonzero(ok), arr, "")
372
+ out += [fact] if fact else []
373
+ for name in names:
374
+ arr = data[name]
375
+ ok = np.isfinite(arr) & (arr > 0)
376
+ shown = name or (label or "value")
377
+ if x_kind == "number" and not log_x and ok.sum() >= 3:
378
+ sel = np.flatnonzero(ok)
379
+ vals = arr[sel]
380
+ turn, kind = None, ""
381
+ if 0 < int(np.argmax(vals)) < sel.size - 1:
382
+ turn, kind = int(np.argmax(vals)), "peak"
383
+ elif 0 < int(np.argmin(vals)) < sel.size - 1:
384
+ turn, kind = int(np.argmin(vals)), "trough"
385
+ if turn is None:
386
+ fact = _slope_fact(shown, sel, arr, "")
387
+ out += [fact] if fact else []
388
+ else:
389
+ at = (x_text or [_x_text(float(v)) for v in xpos])[int(sel[turn])]
390
+ for seg, where in (
391
+ (sel[: turn + 1], f" up to the {kind} at {at}"),
392
+ (sel[turn:], f" from the {kind} at {at} on"),
393
+ ):
394
+ fact = _slope_fact(shown, seg, arr, where)
395
+ out += [fact] if fact else []
396
+ idx = np.flatnonzero(ok)
397
+ if idx.size >= 3 and name not in spiked:
398
+ peak = int(idx[int(np.argmax(arr[idx]))])
399
+ if peak not in (int(idx[0]), int(idx[-1])):
400
+ top = float(arr[peak])
401
+ out.append(
402
+ f"{shown}: peak is {_ratio_text(top / float(arr[idx[0]]))} the first value "
403
+ f"and {_ratio_text(top / float(arr[idx[-1]]))} the last"
404
+ )
405
+ return out
406
+
407
+
408
+ def _reference_crossings(
409
+ ref: tuple[float, str],
410
+ names: Sequence[str],
411
+ data: Mapping[str, np.ndarray],
412
+ xpos: np.ndarray,
413
+ x_kind: str,
414
+ x_text: Sequence[str],
415
+ log: bool,
416
+ log_x: bool,
417
+ label: str | None,
418
+ x_unit: str | None = None,
419
+ noise: float = 0.0,
420
+ unit: str | None = None,
421
+ ) -> list[str]:
422
+ """Where each named series first crosses the reference value.
423
+
424
+ Interpolated linearly between the two bracketing measured x positions (in log
425
+ space on a log axis, matching the straight segments drawn there). Series that
426
+ never cross are skipped, and so is a crossing within ``noise`` of the line on
427
+ both sides (a flat series jittering about it).
428
+ """
429
+ value, ref_text = ref
430
+ # The reference as the caller gave it ("50", not "50.0" from the series' digits).
431
+ ref_fmt = _formatter([value], log=log)
432
+ out: list[str] = []
433
+ target = math.log10(value) if log and value > 0 else value
434
+ stays: dict[tuple[str, bool], list[str]] = {
435
+ (side, strict): [] for strict in (True, False) for side in ("above", "below")
436
+ }
437
+ for name in names:
438
+ arr = data[name]
439
+ idx = np.flatnonzero(np.isfinite(arr))
440
+ if idx.size < 2:
441
+ continue
442
+ ys = np.log10(arr[idx]) if log else arr[idx]
443
+ xs = np.log10(xpos[idx]) if log_x else xpos[idx].astype(float)
444
+ diff = ys - target
445
+ where: str | None = None
446
+ for k in range(idx.size):
447
+ if diff[k] == 0:
448
+ if k == 0:
449
+ continue # starting on the line is not a crossing
450
+ near = [abs(diff[j]) for j in (k - 1, k + 1) if 0 <= j < idx.size]
451
+ if all(v < noise for v in near):
452
+ continue
453
+ at = xs[k]
454
+ exact = True
455
+ elif k + 1 < idx.size and diff[k] * diff[k + 1] < 0:
456
+ if abs(diff[k]) < noise and abs(diff[k + 1]) < noise:
457
+ continue
458
+ t = diff[k] / (diff[k] - diff[k + 1])
459
+ at = xs[k] + t * (xs[k + 1] - xs[k])
460
+ exact = False
461
+ else:
462
+ continue
463
+ if x_kind == "category":
464
+ where = (
465
+ f"at {x_text[idx[k]]}"
466
+ if exact
467
+ else f"between {x_text[idx[k]]} and {x_text[idx[k + 1]]}"
468
+ )
469
+ elif x_kind == "date":
470
+ when = mdates.num2date(float(at)).date().isoformat()
471
+ where = f"at {'' if exact else 'about '}{when}"
472
+ else:
473
+ x_val = 10**at if log_x else at
474
+ where = (
475
+ f"at {'' if exact else 'about '}"
476
+ f"{_with_x_unit(_sig_text(float(x_val), 2), x_unit)}"
477
+ )
478
+ break
479
+ shown = name or (label or "value")
480
+ if where is None:
481
+ # Never crosses: say on which side it stays, so "only X stays above the
482
+ # line" can be checked against every series, not only those that cross.
483
+ for side, strict, holds in (
484
+ ("above", True, (diff >= 0).all()),
485
+ ("below", True, (diff <= 0).all()),
486
+ ("above", False, (diff >= -noise).all()),
487
+ ("below", False, (diff <= noise).all()),
488
+ ):
489
+ if holds:
490
+ stays[(side, strict)].append(shown)
491
+ break
492
+ continue
493
+ named = f" ({ref_text})" if ref_text else ""
494
+ out.append(f"{shown} crosses {_with_unit(ref_fmt(value), unit)}{named} {where}")
495
+ named = f" ({ref_text})" if ref_text else ""
496
+ for (side, strict), who in stays.items():
497
+ if who:
498
+ verb = "stays" if len(who) == 1 else "stay"
499
+ out.append(
500
+ f"{_and_list(who)} {verb} {side} {_with_unit(ref_fmt(value), unit)}{named} throughout"
501
+ + ("" if strict else " (to within noise)")
502
+ )
503
+ return out
504
+
505
+
506
+ def _crossing_fact(
507
+ a: str, b: str, diff: np.ndarray, x_text: Sequence[str], noise: float = 0.0
508
+ ) -> str | None:
509
+ """How often ``a`` and ``b`` swap order, ignoring exact ties.
510
+
511
+ One swap: "a first crosses above b at x". Several: "a and b cross 4 times; a is
512
+ above b from x on", or "...; they end level/tangled" when the last stretch is
513
+ shorter than two points. A swap where the gap is under ``noise`` on both sides
514
+ (two curves level at ~0%, apart only by assay noise) is not a crossing.
515
+ """
516
+ finite = np.flatnonzero(np.isfinite(diff))
517
+ idxs = np.flatnonzero(np.isfinite(diff) & (diff != 0))
518
+ if idxs.size < 2:
519
+ return None
520
+ signs = np.sign(diff[idxs])
521
+ size = np.abs(diff[idxs])
522
+ swaps = np.flatnonzero(
523
+ (signs[1:] != signs[:-1]) & ~((size[1:] < noise) & (size[:-1] < noise))
524
+ )
525
+ if swaps.size == 0:
526
+ return None
527
+ if swaps.size == 1:
528
+ k = int(idxs[int(swaps[0]) + 1])
529
+ before = signs[int(swaps[0])]
530
+ return f"{a} first crosses {'above' if before < 0 else 'below'} {b} at {x_text[k]}"
531
+ last_start = int(swaps[-1]) + 1
532
+ head = f"{a} and {b} cross {swaps.size} times"
533
+ if idxs.size - last_start >= 2:
534
+ side = "above" if signs[last_start] > 0 else "below"
535
+ return f"{head}; {a} is {side} {b} from {x_text[int(idxs[last_start])]} on"
536
+ level = finite.size and int(finite[-1]) != int(idxs[-1])
537
+ return f"{head}; they end {'level' if level else 'tangled'}"
538
+
539
+
540
+ def _trend_baseline_facts(
541
+ compared: Sequence[str],
542
+ base: str,
543
+ data: Mapping[str, np.ndarray],
544
+ x_text: Sequence[str],
545
+ *,
546
+ unit: str | None,
547
+ fmt: str | None,
548
+ log: bool,
549
+ ) -> list[str]:
550
+ """Each series against the baseline: at the last shared x and as the median gap over x."""
551
+ rows: list[tuple[str, int, float, float, np.ndarray]] = []
552
+ for name in compared:
553
+ both = np.flatnonzero(np.isfinite(data[name]) & np.isfinite(data[base]))
554
+ if not both.size:
555
+ continue
556
+ idx = int(both[-1])
557
+ rows.append((name, idx, float(data[name][idx]), float(data[base][idx]), both))
558
+ gaps = [
559
+ g
560
+ for name, idx, va, vb, both in rows
561
+ for g in (va - vb, float(np.median(data[name][both] - data[base][both])))
562
+ ]
563
+ diff_fmt = _formatter(gaps or [0.0], fmt, unit=unit)
564
+ out: list[str] = []
565
+ for name, idx, va, vb, both in rows:
566
+ a, b = data[name][both], data[base][both]
567
+ pos = (a > 0) & (b > 0)
568
+ ratio = float(np.median(a[pos] / b[pos])) if pos.sum() == both.size else float("nan")
569
+ shown = name or "series"
570
+ if log:
571
+ out.append(
572
+ f"{shown} vs {base}: {_ratio_text(va / vb)} at {x_text[idx]}; median ratio "
573
+ f"{_ratio_text(ratio)} over {both.size} shared points"
574
+ )
575
+ continue
576
+ gap = float(np.median(a - b))
577
+ median_text = _diff_with_unit(_signed(diff_fmt(gap)), unit)
578
+ rel = _relative_text(ratio, 1.0, unit) if math.isfinite(ratio) else None
579
+ out.append(
580
+ f"{shown} vs {base}: {_vs_text(va, vb, unit=unit, diff_fmt=diff_fmt)} at "
581
+ f"{x_text[idx]}; median gap {median_text}"
582
+ + (f" ({rel})" if rel else "")
583
+ + f" over {both.size} shared points"
584
+ )
585
+ return out
586
+
587
+
588
+ def _event_facts(
589
+ events: Sequence[tuple[float, str]],
590
+ names: Sequence[str],
591
+ data: Mapping[str, np.ndarray],
592
+ xpos: np.ndarray,
593
+ *,
594
+ unit: str | None,
595
+ fmt: str | None,
596
+ log: bool,
597
+ label: str | None,
598
+ ) -> tuple[list[str], set[str]]:
599
+ """Each series' median before an event and from it on (up to the neighbouring events).
600
+
601
+ "us-west: median 1,500 ms before config change → 2,190 ms from it on (+46%)": the
602
+ fact the event marker exists for. Needs >= 2 finite points on each side. Also
603
+ returns the series whose spike an event marks (stated against the median before it).
604
+ """
605
+ cuts = sorted(pos for pos, _ in events)
606
+ rows: list[tuple[str, str, float, float, float | None]] = []
607
+ for pos, text in events:
608
+ k = cuts.index(pos)
609
+ lo = cuts[k - 1] if k > 0 else -np.inf
610
+ hi = cuts[k + 1] if k + 1 < len(cuts) else np.inf
611
+ for name in names:
612
+ arr = data[name]
613
+ ok = np.isfinite(arr)
614
+ before = arr[ok & (xpos >= lo) & (xpos < pos)]
615
+ after = arr[ok & (xpos >= pos) & (xpos < hi)]
616
+ if before.size < 2 or after.size < 2:
617
+ continue
618
+ # The event day holds the series' peak (a spike): its value is the fact.
619
+ peak = int(np.nanargmax(arr))
620
+ spike = float(arr[peak]) if xpos[peak] == pos else None
621
+ rows.append((name, text, float(np.median(before)), float(np.median(after)), spike))
622
+ if not rows:
623
+ return [], set()
624
+ level_fmt = _formatter(
625
+ [v for r in rows for v in (r[2], r[3], *([r[4]] if r[4] is not None else []))],
626
+ fmt,
627
+ unit=unit,
628
+ log=log,
629
+ )
630
+ diff_fmt = _formatter([r[3] - r[2] for r in rows], fmt, unit=unit)
631
+ out: list[str] = []
632
+ spiked: set[str] = set()
633
+ for name, text, mb, ma, spike in rows:
634
+ if log:
635
+ rel: str | None = _ratio_text(ma / mb) if mb > 0 and ma > 0 else None
636
+ elif unit is not None and unit.strip().startswith("%"):
637
+ rel = _diff_with_unit(_signed(diff_fmt(ma - mb)), unit)
638
+ else:
639
+ rel = _relative_text(ma, mb, None)
640
+ day = ""
641
+ if spike is not None and mb > 0 and spike > 0:
642
+ day = (
643
+ f"; on the {text} day {_with_unit(level_fmt(spike), unit)}, "
644
+ f"{_ratio_text(spike / mb)} the median before"
645
+ )
646
+ spiked.add(name)
647
+ out.append(
648
+ f"{name or (label or 'value')}: median {_with_unit(level_fmt(mb), unit)} before {text} "
649
+ f"\N{RIGHTWARDS ARROW} {_with_unit(level_fmt(ma), unit)} from it on"
650
+ + (f" ({rel})" if rel else "")
651
+ + day
652
+ )
653
+ return out, spiked
654
+
655
+
656
+ def _context_fact(
657
+ rest: Sequence[str],
658
+ data: Mapping[str, np.ndarray],
659
+ *,
660
+ spikes: bool,
661
+ unit: str | None,
662
+ fmt: str | None,
663
+ log: bool,
664
+ ) -> str | None:
665
+ """One fact for the grey context series of a highlighted trend, each against itself.
666
+
667
+ When a highlighted series spikes: how far the others' peaks rise above their own
668
+ medians ("the other 4 peak within 1.6× of their medians"). Otherwise how they moved
669
+ from first to last value: a fold range on a log axis, points for "%" units, a percent
670
+ change where it is meaningful, else the absolute change.
671
+ """
672
+ rest = list(rest)
673
+ if not rest:
674
+ return None
675
+ one = len(rest) == 1
676
+ who = f"the other series, {rest[0]}," if one else f"the other {len(rest)}"
677
+ if spikes:
678
+ ratios = []
679
+ for nm in rest:
680
+ finite = data[nm][np.isfinite(data[nm])]
681
+ med, top = float(np.median(finite)), float(finite.max())
682
+ if med <= 0 or top <= 0:
683
+ return None
684
+ ratios.append(top / med)
685
+ return (
686
+ f"{who} {'peaks' if one else 'peak'} within {_ratio_text(max(ratios))} of "
687
+ f"{'its own median' if one else 'their own medians'}"
688
+ )
689
+ ends = {nm: (_first_finite(data[nm])[1], _last_finite(data[nm])[1]) for nm in rest}
690
+ if log:
691
+ if any(a <= 0 or b <= 0 for a, b in ends.values()):
692
+ return None
693
+ folds = sorted(b / a for a, b in ends.values())
694
+ shown = [_ratio_text(f) for f in (folds[0], folds[-1])]
695
+ span = shown[0] if one or shown[0] == shown[1] else f"{shown[0]} to {shown[1]}"
696
+ noun = "its first value" if one else "their first values"
697
+ return f"{who} {'ends' if one else 'end'} at {span} {noun}"
698
+ points = unit is not None and unit.strip().startswith("%")
699
+ rels = [None if points else _relative_text(b, a, None) for a, b in ends.values()]
700
+ if not points and all(rels):
701
+ by = sorted(ends, key=lambda nm: (ends[nm][1] - ends[nm][0]) / abs(ends[nm][0]))
702
+ lo_t = _relative_text(ends[by[0]][1], ends[by[0]][0], None)
703
+ hi_t = _relative_text(ends[by[-1]][1], ends[by[-1]][0], None)
704
+ else:
705
+ by = sorted(ends, key=lambda nm: ends[nm][1] - ends[nm][0])
706
+ delta_fmt = _formatter([b - a for a, b in ends.values()], fmt, unit=unit)
707
+ lo_t, hi_t = (
708
+ _diff_with_unit(_signed(delta_fmt(ends[nm][1] - ends[nm][0])), unit)
709
+ for nm in (by[0], by[-1])
710
+ )
711
+ span = lo_t if one or lo_t == hi_t else f"{lo_t} to {hi_t}"
712
+ return f"{who} {'changes' if one else 'change'} by {span} from first to last value"
713
+
714
+
715
+ def _first_finite(arr: np.ndarray) -> tuple[int, float]:
716
+ idx = int(np.flatnonzero(np.isfinite(arr))[0])
717
+ return idx, float(arr[idx])
718
+
719
+
720
+ def _last_finite(arr: np.ndarray) -> tuple[int, float]:
721
+ idx = int(np.flatnonzero(np.isfinite(arr))[-1])
722
+ return idx, float(arr[idx])
723
+
724
+
725
+ def _isolated(arr: np.ndarray) -> np.ndarray:
726
+ """Finite points with no finite neighbour on either side (a line cannot show them)."""
727
+ finite = np.isfinite(arr)
728
+ left = np.concatenate([[False], finite[:-1]])
729
+ right = np.concatenate([finite[1:], [False]])
730
+ return finite & ~left & ~right
731
+
732
+
733
+ def _draw_fit_curve(
734
+ ax: Axes,
735
+ xpos: np.ndarray,
736
+ arr: np.ndarray,
737
+ *,
738
+ fit_mode: str,
739
+ color: str,
740
+ scale: float,
741
+ ) -> None:
742
+ """Overlay a dashed OLS trendline (linear, log-linear, or power-law) within finite x span."""
743
+ ok = np.isfinite(xpos) & np.isfinite(arr)
744
+ if fit_mode in {"log", "power"}:
745
+ ok = ok & (arr > 0)
746
+ if fit_mode == "power":
747
+ ok = ok & (xpos > 0)
748
+ if int(ok.sum()) < 3:
749
+ return
750
+ xs = xpos[ok].astype(float)
751
+ ys = arr[ok].astype(float)
752
+ if float(np.ptp(xs)) <= 0:
753
+ return
754
+
755
+ if fit_mode == "power":
756
+ lx, ly = np.log10(xs), np.log10(ys)
757
+ slope, icept = np.polyfit(lx, ly, 1)
758
+ grid_x = np.geomspace(float(xs.min()), float(xs.max()), 60)
759
+ grid_y = 10.0 ** (slope * np.log10(grid_x) + icept)
760
+ elif fit_mode == "log":
761
+ ly = np.log10(ys)
762
+ slope, icept = np.polyfit(xs, ly, 1)
763
+ grid_x = np.linspace(float(xs.min()), float(xs.max()), 60)
764
+ grid_y = 10.0 ** (slope * grid_x + icept)
765
+ else:
766
+ slope, icept = np.polyfit(xs, ys, 1)
767
+ grid_x = np.linspace(float(xs.min()), float(xs.max()), 2)
768
+ grid_y = slope * grid_x + icept
769
+
770
+ ax.plot(
771
+ grid_x,
772
+ grid_y,
773
+ color=color,
774
+ linewidth=1.15 * scale,
775
+ linestyle=(0, (4, 2.5)),
776
+ alpha=0.82,
777
+ zorder=4.5,
778
+ label="_fit",
779
+ )
780
+
781
+
782
+ def _linear_fit_facts(
783
+ names: Sequence[str],
784
+ data: Mapping[str, np.ndarray],
785
+ xpos: np.ndarray,
786
+ *,
787
+ x_kind: str,
788
+ unit: str | None,
789
+ x_unit: str | None,
790
+ label: str | None,
791
+ ) -> list[str]:
792
+ """Compute linear OLS slope (with 95% CI) and R² facts when ``trend(fit='linear'|True)``."""
793
+ out: list[str] = []
794
+ if x_kind == "category":
795
+ return out
796
+ per = f" per {x_unit}" if x_unit else (" per day" if x_kind == "date" else " per x unit")
797
+ for name in names:
798
+ arr = data[name]
799
+ ok = np.isfinite(xpos) & np.isfinite(arr)
800
+ if int(ok.sum()) < 3:
801
+ continue
802
+ xs = xpos[ok].astype(float)
803
+ ys = arr[ok].astype(float)
804
+ if float(np.ptp(xs)) <= 0:
805
+ continue
806
+ slope, icept = np.polyfit(xs, ys, 1)
807
+ resid = ys - (slope * xs + icept)
808
+ total = float(((ys - ys.mean()) ** 2).sum())
809
+ r2 = 1.0 - float((resid**2).sum()) / total if total > 0 else float("nan")
810
+ lo, hi = _slope_ci(xs, ys, float(slope), float(icept))
811
+ ci = ""
812
+ if math.isfinite(lo) and math.isfinite(hi):
813
+ joint = " to " if lo < 0 else "\N{EN DASH}"
814
+ ci = f" (95% CI {_sig_text(lo, 3)}{joint}{_sig_text(hi, 3)})"
815
+ shown = name or (label or "value")
816
+ slope_txt = _diff_with_unit(_signed(_sig_text(float(slope), 3)), unit)
817
+ r2_txt = f", R\N{SUPERSCRIPT TWO} = {r2:.2f}" if math.isfinite(r2) else ""
818
+ out.append(f"{shown}: linear fit slope {slope_txt}{per}{ci}{r2_txt}")
819
+ return out
820
+
821
+
822
+ @_guarded("trend")
823
+ def trend(
824
+ x: Sequence[Any] | str,
825
+ series: Mapping[str, Sequence[float]] | Sequence[float] | str | None = None,
826
+ *,
827
+ y: str | None = None,
828
+ data: Any = None,
829
+ title: str | None = None,
830
+ label: str | None = None,
831
+ unit: str | None = None,
832
+ x_label: str | None = None,
833
+ x_unit: str | None = None,
834
+ highlight: str | Sequence[str] | None = None,
835
+ baseline: str | None = None,
836
+ facet: bool = False,
837
+ band: Any = None,
838
+ band_label: str | None = None,
839
+ points: Any = None,
840
+ points_label: str | None = None,
841
+ events: Mapping[Any, str] | None = None,
842
+ reference: float | tuple[float, str] | None = None,
843
+ zero: bool = False,
844
+ log: bool = False,
845
+ log_y: bool | None = None,
846
+ log_x: bool = False,
847
+ fit: bool | str = False,
848
+ end_values: bool = True,
849
+ fmt: str | None = None,
850
+ callouts: Sequence[tuple[Any, float, str]] | None = None,
851
+ regions: Sequence[tuple[Any, Any, str]] | None = None,
852
+ ) -> Panel:
853
+ """How does it change over time or order? Lines labelled at their ends (no legend).
854
+
855
+ ``x`` is numbers, ISO dates or ordered labels (numeric and date x are sorted
856
+ with their series; repeated x values are refused). ``series`` maps name to
857
+ values (a dict, a pandas DataFrame, or one sequence). For long/tidy rows or
858
+ DataFrames, pass ``data=rows`` with column names: ``mint.trend("x_col",
859
+ "series_col", y="y_col", data=rows)`` (multiple rows per ``(x, series)``
860
+ automatically become raw ``points=`` replicates). At most four series
861
+ get a hue. With more, name the ones the takeaway is about in ``highlight``
862
+ (the rest become grey context) or pass ``facet=True`` for small multiples
863
+ on a shared scale. ``band`` gives a series an uncertainty ribbon: ``(low,
864
+ high)`` sequences, half-widths per x, or one number; say what it is with
865
+ ``band_label``. ``points`` gives raw replicates per x (the line becomes
866
+ their mean). ``log``/``log_y`` and ``log_x`` make an axis logarithmic.
867
+ ``end_values=False`` keeps the end label's name but drops its value.
868
+ ``baseline`` names the reference series (a control, "before"): drawn in ink,
869
+ with every highlighted (or every other) series stated against it in the facts.
870
+ """
871
+ from .._tabular import is_tabular, resolve_trend_table
872
+
873
+ if data is not None:
874
+ if points is not None:
875
+ raise ExplainError(
876
+ "trend() cannot combine data= with an explicit points= mapping.",
877
+ fix_hint="Leave points= out: repeated rows per (x, series) in data= are plotted as points automatically.",
878
+ )
879
+ x, series, points, band = resolve_trend_table(
880
+ data,
881
+ x_col=x,
882
+ y_col=y,
883
+ series_col=series,
884
+ band=band,
885
+ )
886
+ elif y is not None:
887
+ raise ExplainError(
888
+ "trend(y=...) requires data= with row-shaped records or a DataFrame.",
889
+ fix_hint='Pass data=rows, e.g. mint.trend("step", "model", y="acc", data=rows).',
890
+ )
891
+ elif is_tabular(x):
892
+ raise ExplainError(
893
+ "trend() got a table as its first argument without column names.",
894
+ fix_hint='Pass tidy rows via data=: mint.trend("x_col", "series_col", y="y_col", data=rows), '
895
+ 'or pass wide data as mint.trend(df.index, df) after df.pivot(...).',
896
+ )
897
+ log = bool(log or log_y)
898
+ x_kind, xpos, x_text = _parse_x(x)
899
+ n = len(xpos)
900
+ data, single = _series_map(series, n)
901
+ reps: dict[str, list[np.ndarray]] = {}
902
+ if points is not None:
903
+ reps = _replicates(points, n, list(data) if data else [""])
904
+ for name, per_x in reps.items():
905
+ means = np.array([float(r.mean()) if r.size else np.nan for r in per_x])
906
+ if name in data:
907
+ given = data[name]
908
+ both = np.isfinite(given) & np.isfinite(means)
909
+ if not np.allclose(given[both], means[both], rtol=1e-6, atol=1e-12) or np.any(
910
+ np.isfinite(means) != np.isfinite(given)
911
+ ):
912
+ raise ExplainError(
913
+ f"trend(series[{name!r}]) differs from the mean of points[{name!r}].",
914
+ fix_hint="With points=, the line is the mean of the replicates: leave the "
915
+ "series out of series= (or pass series=None).",
916
+ )
917
+ data[name] = means
918
+ if not data:
919
+ raise ExplainError("trend(points) is empty.", fix_hint="Pass at least one series.")
920
+ single = single or (list(reps) == [""])
921
+ if not data:
922
+ raise ExplainError(
923
+ "trend() needs series= (or points= with raw replicates).",
924
+ fix_hint='e.g. mint.trend([1, 2, 3], {"a": [3, 4, 6]}).',
925
+ )
926
+ for name, arr in data.items():
927
+ if np.isfinite(arr).sum() < 2:
928
+ raise ExplainError(
929
+ f"trend(series[{name!r}]) has fewer than two finite values.",
930
+ fix_hint="Drop the series or use compare().",
931
+ )
932
+
933
+ # Numeric and date x are drawn in x order: sort with the series, refuse repeats.
934
+ if x_kind in {"number", "date"}:
935
+ order = np.argsort(xpos, kind="stable")
936
+ if np.any(np.diff(xpos[order]) == 0):
937
+ dup = x_text[int(order[int(np.flatnonzero(np.diff(xpos[order]) == 0)[0])])]
938
+ raise ExplainError(
939
+ f"trend(x) repeats the x value {dup}; a line needs one value per x.",
940
+ fix_hint="Aggregate replicates first: the mean per x in series=, the spread in "
941
+ "band= (with band_label=), or pass the raw replicates as points={name: "
942
+ "[[values at x0], [values at x1], ...]}.",
943
+ )
944
+ if np.any(order != np.arange(n)):
945
+ xpos = xpos[order]
946
+ x_text = [x_text[i] for i in order]
947
+ x_list = list(x)
948
+ x = [x_list[i] for i in order]
949
+ data = {k: v[order] for k, v in data.items()}
950
+ reps = {k: [v[i] for i in order] for k, v in reps.items()}
951
+ if band is not None:
952
+ band = _reorder_band(band, order, n)
953
+
954
+ fit_mode: str | None = None
955
+ if fit is True:
956
+ fit_mode = "power" if (log and log_x) else ("log" if log else "linear")
957
+ elif isinstance(fit, str):
958
+ fit_norm = fit.strip().lower()
959
+ if fit_norm not in {"linear", "log", "power"}:
960
+ raise ExplainError(
961
+ f"trend(fit={fit!r}) must be False, True, 'linear', 'log', or 'power'.",
962
+ fix_hint="Pass fit=True (auto-matches linear/log/log-log axes), fit='linear', or fit='log'.",
963
+ )
964
+ fit_mode = fit_norm
965
+ elif fit is not False and fit is not None:
966
+ raise ExplainError(
967
+ f"trend(fit={fit!r}) must be a bool or 'linear'/'log'/'power'.",
968
+ fix_hint="Pass fit=True or fit='linear'.",
969
+ )
970
+ if fit_mode is not None and x_kind == "category":
971
+ raise ExplainError(
972
+ "trend(fit=...) requires numeric or date x values (cannot fit a regression on categories).",
973
+ fix_hint="Pass numeric/date x values or drop fit=.",
974
+ )
975
+ if log_x:
976
+ if x_kind != "number":
977
+ raise ExplainError(
978
+ "trend(log_x=True) needs numeric x (dose, frequency, 1/T).",
979
+ fix_hint="Pass numbers as x, or drop log_x.",
980
+ )
981
+ if xpos.min() <= 0:
982
+ raise ExplainError(
983
+ "trend(log_x=True) needs strictly positive x values.",
984
+ fix_hint="Drop log_x=True or remove the x positions <= 0.",
985
+ )
986
+
987
+ names = list(data)
988
+ hl = _names(highlight, names)
989
+ base = _baseline_name(baseline, names, hl, "trend")
990
+ if len(names) - (base is not None) > MAX_COLORED_SERIES and not hl and not facet:
991
+ if not _is_strict():
992
+ facet = True
993
+ _record_adjustment(f"trend(): enabled facet=True for {len(names)} series")
994
+ else:
995
+ raise ExplainError(
996
+ f"trend() got {len(names)} series and no highlight; more than "
997
+ f"{MAX_COLORED_SERIES} coloured lines cannot be told apart or held in mind.",
998
+ fix_hint=f"At most {MAX_COLORED_SERIES} series get a colour: pass highlight=[...] "
999
+ f"with the 1-{MAX_HIGHLIGHTS} series the takeaway names (others turn grey), or "
1000
+ f"facet=True for small multiples (up to {MAX_FACETS}).",
1001
+ rule="too_many_series",
1002
+ )
1003
+ if facet and len(names) > MAX_FACETS:
1004
+ if not _is_strict():
1005
+ keep = list(dict.fromkeys([*hl, *([base] if base else [])]))
1006
+ by_span = sorted(
1007
+ names,
1008
+ key=lambda nm: float(np.nanmax(data[nm]) - np.nanmin(data[nm])),
1009
+ reverse=True,
1010
+ )
1011
+ for nm in by_span:
1012
+ if len(keep) >= MAX_FACETS:
1013
+ break
1014
+ if nm not in keep:
1015
+ keep.append(nm)
1016
+ keep_set = set(keep)
1017
+ data = {nm: data[nm] for nm in names if nm in keep_set}
1018
+ reps = {nm: reps[nm] for nm in reps if nm in keep_set}
1019
+ _record_adjustment(f"trend(facet=True): trimmed {len(names)} series to top {len(data)}")
1020
+ names = list(data)
1021
+ else:
1022
+ raise ExplainError(
1023
+ f"trend(facet=True) got {len(names)} series; more than {MAX_FACETS} small "
1024
+ "multiples is a wall.",
1025
+ fix_hint=f"facet=True takes at most {MAX_FACETS} series: keep the most relevant "
1026
+ f"ones, or drop facet= and highlight 1-{MAX_HIGHLIGHTS} in one panel (any number "
1027
+ "of the rest stay grey).",
1028
+ rule="too_many_series",
1029
+ )
1030
+ ref = _reference_line(reference, "trend(reference)")
1031
+ bands, band_spec, band_modes = _trend_bands(band, data, n)
1032
+ event_items: list[tuple[float, str]] = [
1033
+ (_parse_x_point(at, x_kind, x_text, "trend(events) key"), str(text))
1034
+ for at, text in (events or {}).items()
1035
+ ]
1036
+ region_items, regions_spec = _parse_trend_regions(regions, x_kind, x_text, log_x=log_x)
1037
+ callout_items, callouts_spec = _parse_trend_callouts(
1038
+ callouts, x_kind, x_text, log_x=log_x, log_y=log
1039
+ )
1040
+
1041
+ all_values = np.concatenate([v[np.isfinite(v)] for v in data.values()])
1042
+ rep_values = np.concatenate([r for per_x in reps.values() for r in per_x] or [np.empty(0)])
1043
+ if log and (all_values.min() <= 0 or (rep_values.size and rep_values.min() <= 0)):
1044
+ raise ExplainError(
1045
+ "trend(log=True) needs strictly positive values.",
1046
+ fix_hint="Drop log=True or remove non-positive values.",
1047
+ )
1048
+ if log and ref is not None and ref[0] <= 0:
1049
+ raise ExplainError(
1050
+ "trend(reference) must be positive on a log axis.",
1051
+ fix_hint="Drop the reference or log=True.",
1052
+ )
1053
+ fmt_fn = _formatter(list(all_values), fmt, unit=unit, log=log)
1054
+ # Crossings closer than this on both sides are noise, not a change of order: 3% of
1055
+ # the panel's value range (in decades on a log axis), or with raw replicates the 95%
1056
+ # half-width of a difference of two means when that is larger (assay noise at ~0%).
1057
+ noise = 0.03 * float(np.ptp(np.log10(all_values) if log else all_values))
1058
+ spreads = [
1059
+ (float(np.std(np.log10(r) if log else r, ddof=1)), r.size)
1060
+ for per_x in reps.values()
1061
+ for r in per_x
1062
+ if r.size >= 2
1063
+ ]
1064
+ if spreads:
1065
+ sd = float(np.median([sp for sp, _ in spreads]))
1066
+ n_rep = float(np.median([k for _, k in spreads]))
1067
+ noise = max(noise, 1.96 * sd * math.sqrt(2.0 / n_rep))
1068
+
1069
+ _last = _last_finite
1070
+ _first = _first_finite
1071
+
1072
+ colored = hl if hl else ([] if facet else names)
1073
+ # Coloured series other than the baseline (which is drawn in ink, not a palette colour).
1074
+ focus = [nm for nm in colored if nm != base]
1075
+ drawn = [base, *focus] if (base is not None and not facet) else colored
1076
+ issues: list[dict[str, Any]] = []
1077
+ if bands and not band_label:
1078
+ issues.append(_interval_issue("trend", "band", "band_label"))
1079
+
1080
+ # x values in facts carry the unit: x_unit=, else the end of x_label ("4 h", not "4").
1081
+ x_unit_given = x_unit
1082
+ x_unit = _resolve_x_unit(x_unit, x_label, "trend") if x_kind == "number" else None
1083
+ xt = [_with_x_unit(t, x_unit) for t in x_text]
1084
+ facts: list[str] = []
1085
+ described = list((hl or names)[:6])
1086
+ if base is not None and base not in described:
1087
+ described.append(base)
1088
+ for name in described:
1089
+ arr = data[name]
1090
+ i0, v0 = _first(arr)
1091
+ i1, v1 = _last(arr)
1092
+ finite = arr[np.isfinite(arr)]
1093
+ moved = _change_text(
1094
+ v0,
1095
+ v1,
1096
+ series_range=float(finite.max() - finite.min()),
1097
+ unit=unit,
1098
+ diff_fmt=_formatter([v1 - v0], fmt, unit=unit),
1099
+ log=log,
1100
+ )
1101
+ peak = int(np.nanargmax(arr))
1102
+ shown = name or (label or "value")
1103
+ missing = int((~np.isfinite(arr)).sum())
1104
+ facts.append(
1105
+ # The unit on both values, as change() writes them: "0.0059% → 0.0062%".
1106
+ f"{shown}: {_with_unit(fmt_fn(v0), unit)} \N{RIGHTWARDS ARROW} {_with_unit(fmt_fn(v1), unit)} "
1107
+ f"from {xt[i0]} to {xt[i1]}"
1108
+ + (f" ({moved})" if moved else "")
1109
+ + f"; peak {_with_unit(fmt_fn(float(arr[peak])), unit)} at {xt[peak]}"
1110
+ + (f"; {missing} of {n} points missing" if missing else "")
1111
+ )
1112
+ # Alt text: every described series (highlighted ones and the baseline, or all).
1113
+ alt_facts = list(facts)
1114
+ event_facts: list[str] = []
1115
+ spiked: set[str] = set()
1116
+ if event_items and x_kind in {"number", "date"}:
1117
+ event_series = list(hl) if hl else (list(names) if len(names) <= MAX_COLORED_SERIES else [])
1118
+ if base is not None and base not in event_series:
1119
+ event_series.append(base)
1120
+ event_facts, spiked = _event_facts(
1121
+ event_items, event_series, data, xpos, unit=unit, fmt=fmt, log=log, label=label
1122
+ )
1123
+ spikes = bool(spiked)
1124
+ for name in described:
1125
+ if name in spiked:
1126
+ # An event marks this spike: it is stated against the median before the
1127
+ # event (one "usual" level), not also against the whole period's median.
1128
+ continue
1129
+ # A spike: the peak far above the series' typical level, stated against its median.
1130
+ arr = data[name]
1131
+ finite = arr[np.isfinite(arr)]
1132
+ med = float(np.median(finite))
1133
+ peak = int(np.nanargmax(arr))
1134
+ top = float(arr[peak])
1135
+ if med > 0 and top > 0 and (
1136
+ math.log10(top / med) >= 0.7 if log else top >= 5.0 * med
1137
+ ):
1138
+ spikes = True
1139
+ facts.append(
1140
+ f"{name or (label or 'value')}: peak {_with_unit(fmt_fn(top), unit)} "
1141
+ f"{'on' if x_kind == 'date' else 'at'} {xt[peak]}, "
1142
+ f"{_ratio_text(top / med)} its median"
1143
+ )
1144
+ if hl:
1145
+ context = _context_fact(
1146
+ [nm for nm in names if nm not in hl and nm != base],
1147
+ data,
1148
+ spikes=spikes,
1149
+ unit=unit,
1150
+ fmt=fmt,
1151
+ log=log,
1152
+ )
1153
+ if context:
1154
+ facts.append(context)
1155
+ if log:
1156
+ facts.extend(
1157
+ _log_trend_facts(
1158
+ data,
1159
+ described,
1160
+ xpos,
1161
+ x_kind,
1162
+ log_x,
1163
+ label,
1164
+ xt,
1165
+ x_unit,
1166
+ spiked,
1167
+ power_names=[*described, *(nm for nm in names if nm not in described)][:6],
1168
+ )
1169
+ )
1170
+ for name in names:
1171
+ if name not in described and (~np.isfinite(data[name])).any():
1172
+ facts.append(
1173
+ f"{name or 'series'}: {int((~np.isfinite(data[name])).sum())} of {n} points missing"
1174
+ )
1175
+ if base is not None:
1176
+ facts.extend(
1177
+ _trend_baseline_facts(
1178
+ [nm for nm in (hl or names) if nm != base][:6],
1179
+ base,
1180
+ data,
1181
+ xt,
1182
+ unit=unit,
1183
+ fmt=fmt,
1184
+ log=log,
1185
+ )
1186
+ )
1187
+ elif 2 <= len(colored) <= MAX_COLORED_SERIES:
1188
+ a = colored[0]
1189
+ for b in colored[1:4]:
1190
+ both = np.flatnonzero(np.isfinite(data[a]) & np.isfinite(data[b]))
1191
+ if not both.size:
1192
+ continue
1193
+ idx = int(both[-1])
1194
+ va, vb = float(data[a][idx]), float(data[b][idx])
1195
+ if log:
1196
+ ratio = va / vb
1197
+ rel = (
1198
+ f"{_ratio_text(ratio)} {b}"
1199
+ if ratio >= 1
1200
+ else f"{_ratio_text(1 / ratio)} below {b}"
1201
+ )
1202
+ facts.append(f"at {xt[idx]}: {a} is {rel}")
1203
+ else:
1204
+ gap_fmt = _formatter([abs(va - vb)], fmt, unit=unit)
1205
+ if va == vb:
1206
+ facts.append(f"at {xt[idx]}: {a} equals {b}")
1207
+ else:
1208
+ facts.append(
1209
+ f"at {xt[idx]}: {a} is {_diff_with_unit(_unsigned(gap_fmt(abs(va - vb))), unit)} "
1210
+ f"{'above' if va > vb else 'below'} {b}"
1211
+ )
1212
+ crossing_pairs: list[tuple[str, str]] = []
1213
+ if base is not None:
1214
+ crossing_pairs = [(nm, base) for nm in (hl or names) if nm != base][:6]
1215
+ elif 2 <= len(colored) <= MAX_COLORED_SERIES:
1216
+ crossing_pairs = [(colored[0], other) for other in colored[1:]]
1217
+ for a, b in crossing_pairs:
1218
+ gap = np.log10(data[a]) - np.log10(data[b]) if log else data[a] - data[b]
1219
+ crossed = _crossing_fact(a, b, gap, xt, noise)
1220
+ if crossed:
1221
+ facts.append(crossed)
1222
+ facts.extend(event_facts)
1223
+ if ref is not None:
1224
+ facts.extend(
1225
+ _reference_crossings(
1226
+ # Highlighted series first, then the grey context ones: a potency claim
1227
+ # ("10x below the others") needs every curve's crossing.
1228
+ ref,
1229
+ [*hl, *(nm for nm in names if nm not in hl)][:6],
1230
+ data,
1231
+ xpos,
1232
+ x_kind,
1233
+ xt,
1234
+ log,
1235
+ log_x,
1236
+ label,
1237
+ x_unit,
1238
+ noise,
1239
+ unit,
1240
+ )
1241
+ )
1242
+ if reps:
1243
+ dot_word = (points_label or "").strip() or "replicates"
1244
+ for name, per_x in reps.items():
1245
+ counts = [r.size for r in per_x]
1246
+ measured = [c for c in counts if c]
1247
+ lo_n, hi_n = min(measured, default=0), max(measured, default=0)
1248
+ facts.append(
1249
+ f"{name or (label or 'values')}: line is the mean of n = "
1250
+ + (f"{lo_n}" if lo_n == hi_n else f"{lo_n}\N{EN DASH}{hi_n}")
1251
+ + f" {dot_word} per x"
1252
+ )
1253
+ if bands:
1254
+ facts.append(_interval_mode_text(band_modes, "bands"))
1255
+ if fit_mode == "linear":
1256
+ facts.extend(
1257
+ _linear_fit_facts(
1258
+ colored,
1259
+ data,
1260
+ xpos,
1261
+ x_kind=x_kind,
1262
+ unit=unit,
1263
+ x_unit=x_unit,
1264
+ label=label,
1265
+ )
1266
+ )
1267
+
1268
+ describe = (
1269
+ f"{'Small-multiple line charts' if facet else 'Line chart'} of {label or 'values'}"
1270
+ + (f" ({unit})" if unit else "")
1271
+ + (" on a log scale" if log else "")
1272
+ + f" over {x_label or 'x'}"
1273
+ + (" (log scale)" if log_x else "")
1274
+ + f" from {x_text[0]} to {x_text[-1]}, {len(names)} series"
1275
+ + (f", shaded bands show {band_label}" if bands and band_label else "")
1276
+ )
1277
+ show_markers = n <= 12
1278
+
1279
+ def _setup_x(
1280
+ ax: Axes, sizes: _Sizes, theme: Theme = MINTFIG_THEME, *, sparse: bool = False
1281
+ ) -> None:
1282
+ minus = theme.minus_sign
1283
+ if log_x:
1284
+ ax.set_xscale("log")
1285
+ ax.set_xlim(float(xpos.min()), float(xpos.max()))
1286
+ ax.xaxis.set_minor_formatter(NullFormatter())
1287
+ _narrow_log_ticks(ax.xaxis, float(xpos.min()), float(xpos.max()), minus, extend=False)
1288
+ return
1289
+ ax.set_xlim(float(xpos.min()), float(xpos.max()))
1290
+ if x_kind == "date":
1291
+ locator = mdates.AutoDateLocator(minticks=2, maxticks=3 if sparse else 6)
1292
+ ax.xaxis.set_major_locator(locator)
1293
+ ax.xaxis.set_major_formatter(_date_formatter(locator))
1294
+ elif x_kind == "category":
1295
+ limit = 3 if sparse else 8
1296
+ step = max(1, math.ceil(len(xpos) / limit))
1297
+ shown = list(range(0, len(xpos), step))
1298
+ ax.set_xticks(xpos[shown], [_plain(x_text[i], theme) for i in shown])
1299
+ else:
1300
+ whole = bool(np.all(xpos == np.round(xpos)))
1301
+ years = whole and 1000 <= xpos.min() and xpos.max() <= 2200
1302
+ if len(xpos) <= 8:
1303
+ # Few measured positions (doping 0, 0.5, 1, 2, 4): tick exactly there;
1304
+ # labels that would touch are thinned after layout (_fit_ticks).
1305
+ ax.xaxis.set_major_locator(FixedLocator(xpos.tolist()))
1306
+ else:
1307
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=3 if sparse else 6, integer=whole))
1308
+ ax.xaxis.set_major_formatter(
1309
+ FuncFormatter(
1310
+ lambda v, _p, m=minus, a=ax.xaxis: f"{v:.0f}" if years else _tick_label(v, m, a)
1311
+ )
1312
+ )
1313
+
1314
+ def _ylimits() -> tuple[float, float]:
1315
+ lows = [all_values.min()] + [np.nanmin(b[0]) for b in bands.values()]
1316
+ highs = [all_values.max()] + [np.nanmax(b[1]) for b in bands.values()]
1317
+ if rep_values.size:
1318
+ lows.append(rep_values.min())
1319
+ highs.append(rep_values.max())
1320
+ if ref is not None:
1321
+ lows.append(ref[0])
1322
+ highs.append(ref[0])
1323
+ lo, hi = float(min(lows)), float(max(highs))
1324
+ if log:
1325
+ lo = max(lo, float(all_values.min()) / 10.0) if lo <= 0 else lo
1326
+ return lo / 1.15, hi * 1.15
1327
+ span = (hi - lo) or abs(hi) or 1.0
1328
+ bottom = 0.0 if (zero and lo >= 0) else lo - 0.06 * span
1329
+ return bottom, hi + 0.08 * span
1330
+
1331
+ def _decorate(
1332
+ ctx: _Ctx, ax: Axes, sizes: _Sizes
1333
+ ) -> tuple[list[Any], list[Any], tuple[Any, ...] | None]:
1334
+ """Reference and event rules.
1335
+
1336
+ Returns (event labels with their rules, other labels, the reference label
1337
+ with its line for :func:`_place_reference_label`, or None).
1338
+ """
1339
+ theme = ctx.theme
1340
+ others: list[Any] = []
1341
+ events_drawn: list[Any] = []
1342
+ ref_drawn: tuple[Any, ...] | None = None
1343
+ for r_x0, r_x1, _r_text in region_items:
1344
+ ax.axvspan(
1345
+ r_x0,
1346
+ r_x1,
1347
+ color=theme.context_fill,
1348
+ alpha=0.12,
1349
+ linewidth=0,
1350
+ zorder=0,
1351
+ )
1352
+ if ref is not None:
1353
+ ref_line = ax.axhline(
1354
+ ref[0], color=theme.ink, linewidth=0.7, linestyle=(0, (3, 2)), zorder=2
1355
+ )
1356
+ if ref[1]:
1357
+ # Inline-tick styles print tick values at the left edge: label on the right.
1358
+ right = theme.inline_y_ticks
1359
+ ref_note = ax.annotate(
1360
+ _plain(ref[1], theme),
1361
+ (1.0 if right else 0.0, ref[0]),
1362
+ xycoords=("axes fraction", "data"),
1363
+ xytext=(-2.0 if right else 2.0, 2.5),
1364
+ textcoords="offset points",
1365
+ ha="right" if right else "left",
1366
+ va="bottom",
1367
+ fontsize=sizes.small,
1368
+ color=theme.muted,
1369
+ bbox=ctx.halo_bbox(0.1),
1370
+ )
1371
+ others.append(ref_note)
1372
+ ref_drawn = (ref_note, ref_line, ref[1], right)
1373
+ lo_x, hi_x = (
1374
+ (math.log10(xpos.min()), math.log10(xpos.max())) if log_x else (xpos.min(), xpos.max())
1375
+ )
1376
+ for pos, text in event_items:
1377
+ rule = ax.axvline(pos, color=theme.axis, linewidth=0.6, zorder=1)
1378
+ at = math.log10(pos) if (log_x and pos > 0) else pos
1379
+ near_right = at > lo_x + 0.7 * (hi_x - lo_x)
1380
+ note = ax.annotate(
1381
+ _plain(text, theme),
1382
+ (pos, 1.0),
1383
+ xycoords=("data", "axes fraction"),
1384
+ xytext=(-3.0 if near_right else 3.0, -2.0),
1385
+ textcoords="offset points",
1386
+ ha="right" if near_right else "left",
1387
+ va="top",
1388
+ fontsize=sizes.small,
1389
+ color=theme.muted,
1390
+ bbox=ctx.halo_bbox(0.1),
1391
+ )
1392
+ events_drawn.append((note, rule, pos, text, near_right))
1393
+ return events_drawn, others, ref_drawn
1394
+
1395
+ def _measured_points(
1396
+ ax: Axes, name: str, col: str, sizes: _Sizes, theme: Theme, *, context: bool = False
1397
+ ) -> None:
1398
+ """Replicates as pale dots; a marker at each measurement when x is sparse; lone points."""
1399
+ if name in reps:
1400
+ rx = np.concatenate([np.full(r.size, xpos[i]) for i, r in enumerate(reps[name])])
1401
+ ry = np.concatenate(reps[name])
1402
+ ax.scatter(
1403
+ rx,
1404
+ ry,
1405
+ s=(2.4 * sizes.scale) ** 2,
1406
+ color=col,
1407
+ # Context replicates are pale grey already: at the coloured series' alpha
1408
+ # they vanish, so they stay grey but nearly opaque.
1409
+ alpha=0.3 if not context else 0.7,
1410
+ linewidth=0,
1411
+ zorder=3,
1412
+ clip_on=False,
1413
+ )
1414
+ arr = data[name]
1415
+ mask = np.isfinite(arr) if show_markers else _isolated(arr)
1416
+ if mask.any():
1417
+ ax.plot(
1418
+ xpos[mask],
1419
+ arr[mask],
1420
+ linestyle="none",
1421
+ marker="o",
1422
+ markersize=(2.2 if context else 2.8) * sizes.scale,
1423
+ color=col,
1424
+ markeredgecolor=theme.background,
1425
+ markeredgewidth=0.4,
1426
+ zorder=3 if context else 4,
1427
+ label="_points",
1428
+ clip_on=False,
1429
+ )
1430
+
1431
+ # ---- single panel with direct labels --------------------------------- #
1432
+ def _draw(ctx: _Ctx, ax: Axes) -> Callable[[], None]:
1433
+ sz = ctx.sizes
1434
+ theme = ctx.theme
1435
+ palette = theme.accent_colors if hl else theme.series_colors
1436
+ color_of = {
1437
+ name: ctx.colors.get(
1438
+ name,
1439
+ theme.ink
1440
+ if name == base
1441
+ else (ctx.default_color if not name else palette[i % len(palette)]),
1442
+ )
1443
+ for i, name in enumerate(drawn)
1444
+ }
1445
+ effects = ctx.line_effects()
1446
+ if log:
1447
+ ax.set_yscale("log")
1448
+ _value_axis(ax, sz, theme)
1449
+ _setup_x(ax, sz, theme)
1450
+ ax.set_ylim(*_ylimits())
1451
+ y0, y1 = ax.get_ylim()
1452
+ if log:
1453
+ y0, y1 = _narrow_log_ticks(ax.yaxis, y0, y1, theme.minus_sign, data_hi=y1 / 1.15)
1454
+ ax.set_ylim(y0, y1)
1455
+ if theme.hide_spines and not log and y0 <= 0.0 <= y1:
1456
+ ax.axhline(0.0, color=theme.zero_line, linewidth=theme.zero_line_lw, zorder=2)
1457
+ if theme.inline_y_ticks and not log:
1458
+ _apply_inline_y_ticks(ax, sz, theme, unit=unit)
1459
+ if x_label:
1460
+ ax.set_xlabel(_plain(x_label, theme), fontsize=sz.small, color=theme.muted, labelpad=2)
1461
+
1462
+ context = [nm for nm in names if nm not in color_of]
1463
+ for name in context:
1464
+ line_kw: dict[str, Any] = {
1465
+ "color": theme.context_line,
1466
+ "linewidth": theme.context_line_lw * sz.scale,
1467
+ "zorder": 2,
1468
+ "label": "_context",
1469
+ }
1470
+ if effects is not None:
1471
+ line_kw["path_effects"] = effects
1472
+ ax.plot(xpos, data[name], **line_kw)
1473
+ _measured_points(ax, name, theme.context_line, sz, theme, context=True)
1474
+ for name in drawn:
1475
+ col = color_of[name]
1476
+ if name in bands:
1477
+ ax.fill_between(
1478
+ xpos,
1479
+ bands[name][0],
1480
+ bands[name][1],
1481
+ color=col,
1482
+ alpha=0.14,
1483
+ linewidth=0,
1484
+ zorder=2,
1485
+ )
1486
+ line_kw = {
1487
+ "color": col,
1488
+ "linewidth": theme.line_lw * sz.scale,
1489
+ "zorder": 4,
1490
+ "label": name or "_single",
1491
+ "solid_capstyle": theme.line_capstyle,
1492
+ }
1493
+ if effects is not None:
1494
+ line_kw["path_effects"] = effects
1495
+ ax.plot(xpos, data[name], **line_kw)
1496
+ if fit_mode is not None:
1497
+ _draw_fit_curve(ax, xpos, data[name], fit_mode=fit_mode, color=col, scale=sz.scale)
1498
+ _measured_points(ax, name, col, sz, theme)
1499
+ i1, v1 = _last(data[name])
1500
+ ax.plot(
1501
+ [xpos[i1]],
1502
+ [v1],
1503
+ marker="o",
1504
+ markersize=3.6 * sz.scale,
1505
+ color=col,
1506
+ markeredgecolor=theme.background,
1507
+ markeredgewidth=0.6,
1508
+ zorder=5,
1509
+ label="_end",
1510
+ clip_on=False,
1511
+ )
1512
+ events_drawn, other_notes, ref_drawn = _decorate(ctx, ax, sz)
1513
+
1514
+ label_context = bool(context) and len(names) <= 8
1515
+ entries: list[tuple[str, float, float, str, str, str]] = []
1516
+ for name in drawn:
1517
+ i1, v1 = _last(data[name])
1518
+ if not name:
1519
+ if not end_values:
1520
+ continue
1521
+ text = _with_unit(fmt_fn(v1), unit)
1522
+ else:
1523
+ text = f"{name} {fmt_fn(v1)}" if end_values else name
1524
+ weight = "normal" if name == base else "bold"
1525
+ entries.append(
1526
+ (text, float(xpos[i1]), v1, ctx.text_color(color_of[name]), weight, color_of[name])
1527
+ )
1528
+ if label_context:
1529
+ for name in context:
1530
+ i1, v1 = _last(data[name])
1531
+ entries.append(
1532
+ (name, float(xpos[i1]), v1, theme.muted, "normal", theme.context_line)
1533
+ )
1534
+ elif context:
1535
+ mid = sorted(context, key=lambda nm: _last(data[nm])[1])[len(context) // 2]
1536
+ i1, v1 = _last(data[mid])
1537
+ entries.append(
1538
+ (
1539
+ f"{len(context)} others",
1540
+ float(xpos[i1]),
1541
+ v1,
1542
+ theme.muted,
1543
+ "normal",
1544
+ theme.context_line,
1545
+ )
1546
+ )
1547
+
1548
+ annotations = [
1549
+ ax.annotate(
1550
+ _plain(text, theme),
1551
+ (px, py),
1552
+ xytext=(6.0, 0.0),
1553
+ textcoords="offset points",
1554
+ ha="left",
1555
+ va="center",
1556
+ fontsize=sz.small,
1557
+ color=text_color,
1558
+ fontweight=weight,
1559
+ annotation_clip=False,
1560
+ )
1561
+ for text, px, py, text_color, weight, _ in entries
1562
+ ]
1563
+
1564
+ def _finish() -> None:
1565
+ _relax_end_labels()
1566
+ _clear_inline_ticks(ctx, ax)
1567
+ _place_reference_label(ctx, ax, ref_drawn, annotations)
1568
+ _place_event_labels(ctx, ax, events_drawn, [*annotations, *other_notes])
1569
+ if region_items:
1570
+ _place_region_labels(ctx, ax, region_items, log_x=log_x)
1571
+ if callout_items:
1572
+ _place_callouts(ctx, ax, callout_items)
1573
+
1574
+ def _relax_end_labels() -> None:
1575
+ if not annotations:
1576
+ return
1577
+ renderer = ctx.fig.canvas.get_renderer()
1578
+ box = ax.get_window_extent(renderer)
1579
+ k = ctx.pt_per_px
1580
+ ys = np.array([ax.transData.transform((e[1], e[2]))[1] * k for e in entries])
1581
+ placed = _relax_positions_pt(
1582
+ ys, sz.small * 1.22, box.y0 * k + sz.small * 0.4, box.y1 * k - sz.small * 0.4
1583
+ )
1584
+ for ann, entry, y0, y1 in zip(annotations, entries, ys, placed, strict=True):
1585
+ shift = float(y1 - y0)
1586
+ ann.set_position((6.0, shift))
1587
+ if abs(shift) > sz.small * 0.75:
1588
+ ax.annotate(
1589
+ "",
1590
+ (entry[1], entry[2]),
1591
+ xytext=(5.0, shift),
1592
+ textcoords="offset points",
1593
+ arrowprops={
1594
+ "arrowstyle": "-",
1595
+ "color": entry[5],
1596
+ "linewidth": 0.5,
1597
+ "shrinkA": 0,
1598
+ "shrinkB": 2.5,
1599
+ },
1600
+ annotation_clip=False,
1601
+ )
1602
+
1603
+ return _finish
1604
+
1605
+ # ---- small multiples -------------------------------------------------- #
1606
+ def _facet_grid(cell_width_mm: float) -> tuple[int, int]:
1607
+ ncols = max(1, min(len(names), int(cell_width_mm // 30.0), 4))
1608
+ return math.ceil(len(names) / ncols), ncols
1609
+
1610
+ def _facet_frames(ctx: _Ctx, ax: Axes, rect: Bbox) -> list[tuple[Axes, Bbox]]:
1611
+ sz = ctx.sizes
1612
+ theme = ctx.theme
1613
+ effects = ctx.line_effects()
1614
+ ax.remove()
1615
+ nrows, ncols = _facet_grid(ctx.cell_width_mm)
1616
+ px_per_mm = float(ctx.fig.dpi) / 25.4
1617
+ gap_x, gap_y = 4.0 * px_per_mm * sz.scale, 4.5 * px_per_mm * sz.scale
1618
+ cell_w = (rect.width - gap_x * (ncols - 1)) / ncols
1619
+ cell_h = (rect.height - gap_y * (nrows - 1)) / nrows
1620
+ ylim = _ylimits()
1621
+ frames: list[tuple[Axes, Bbox]] = []
1622
+ facet_events: list[tuple[Axes, list[Any], list[Any]]] = []
1623
+ first: Axes | None = None
1624
+ for idx, name in enumerate(names):
1625
+ r, c = divmod(idx, ncols)
1626
+ x0 = rect.x0 + c * (cell_w + gap_x)
1627
+ y1 = rect.y1 - r * (cell_h + gap_y)
1628
+ sub = Bbox.from_extents(x0, y1 - cell_h, x0 + cell_w, y1)
1629
+ child = ctx.fig.add_axes([0.1, 0.1, 0.5, 0.5], sharey=first)
1630
+ first = first or child
1631
+ ctx.tag(child)
1632
+ ctx.extra_axes.append(child)
1633
+ if log:
1634
+ child.set_yscale("log")
1635
+ _value_axis(child, sz, theme, nbins=3)
1636
+ _setup_x(child, sz, theme, sparse=True)
1637
+ child.set_ylim(*ylim)
1638
+ if log:
1639
+ child.set_ylim(
1640
+ *_narrow_log_ticks(
1641
+ child.yaxis,
1642
+ ylim[0],
1643
+ ylim[1],
1644
+ theme.minus_sign,
1645
+ max_ticks=4,
1646
+ data_hi=ylim[1] / 1.15,
1647
+ )
1648
+ )
1649
+ if name == base:
1650
+ col = ctx.colors.get(name, theme.ink)
1651
+ else:
1652
+ col = theme.accent_colors[hl.index(name)] if name in hl else theme.default_color
1653
+ ghost_col = theme.context_fill
1654
+ for other in names:
1655
+ if other != name:
1656
+ child.plot(
1657
+ xpos,
1658
+ data[other],
1659
+ color=ghost_col,
1660
+ linewidth=0.7 * sz.scale,
1661
+ zorder=1,
1662
+ label="_ghost",
1663
+ )
1664
+ if name in bands:
1665
+ child.fill_between(
1666
+ xpos,
1667
+ bands[name][0],
1668
+ bands[name][1],
1669
+ color=col,
1670
+ alpha=0.14,
1671
+ linewidth=0,
1672
+ zorder=2,
1673
+ )
1674
+ line_kw: dict[str, Any] = {
1675
+ "color": col,
1676
+ "linewidth": theme.facet_line_lw * sz.scale,
1677
+ "zorder": 3,
1678
+ "label": "_series",
1679
+ "solid_capstyle": theme.line_capstyle,
1680
+ }
1681
+ if effects is not None:
1682
+ line_kw["path_effects"] = effects
1683
+ child.plot(xpos, data[name], **line_kw)
1684
+ if fit_mode is not None:
1685
+ _draw_fit_curve(child, xpos, data[name], fit_mode=fit_mode, color=col, scale=sz.scale)
1686
+ _measured_points(child, name, col, sz, theme)
1687
+ i1, v1 = _last(data[name])
1688
+ child.plot(
1689
+ [xpos[i1]],
1690
+ [v1],
1691
+ marker="o",
1692
+ markersize=3.2 * sz.scale,
1693
+ color=col,
1694
+ markeredgecolor=theme.background,
1695
+ markeredgewidth=0.6,
1696
+ zorder=4,
1697
+ clip_on=False,
1698
+ label="_end",
1699
+ )
1700
+ child_events, child_notes, child_ref = _decorate(ctx, child, sz)
1701
+ facet_events.append((child, child_events, child_notes, child_ref))
1702
+ child.set_title(
1703
+ _plain(f"{name} {fmt_fn(v1)}" if end_values else name, theme),
1704
+ loc="left",
1705
+ fontsize=sz.small,
1706
+ fontweight="bold",
1707
+ color=ctx.text_color(col) if name in hl else theme.ink,
1708
+ pad=3.0,
1709
+ )
1710
+ child.tick_params(axis="y", labelleft=(c == 0))
1711
+ last_in_column = idx + ncols >= len(names)
1712
+ child.tick_params(axis="x", labelbottom=last_in_column)
1713
+ frames.append((child, sub))
1714
+
1715
+ def _equalize() -> None:
1716
+ """Give every small multiple the same plot width (only column one has y labels)."""
1717
+ fig_w = ctx.fig.bbox.width
1718
+ gutter = frames[0][0].get_position().x0 * fig_w - rect.x0
1719
+ plot_w = (rect.width - gutter - gap_x * (ncols - 1)) / ncols
1720
+ for idx, (child, _sub) in enumerate(frames):
1721
+ pos = child.get_position()
1722
+ left = rect.x0 + gutter + (idx % ncols) * (plot_w + gap_x)
1723
+ child.set_position([left / fig_w, pos.y0, plot_w / fig_w, pos.height])
1724
+
1725
+ ctx.finishers.append(_equalize)
1726
+ for idx_f, (child, child_events, child_notes, child_ref) in enumerate(facet_events):
1727
+ if child_ref is not None:
1728
+ ctx.finishers.append(
1729
+ functools.partial(
1730
+ _place_reference_label,
1731
+ ctx,
1732
+ child,
1733
+ child_ref,
1734
+ [getattr(child, "_left_title", None)],
1735
+ )
1736
+ )
1737
+ if child_events:
1738
+ ctx.finishers.append(
1739
+ functools.partial(
1740
+ _place_event_labels,
1741
+ ctx,
1742
+ child,
1743
+ child_events,
1744
+ [*child_notes, getattr(child, "_left_title", None)],
1745
+ )
1746
+ )
1747
+ if idx_f == 0 and region_items:
1748
+ ctx.finishers.append(
1749
+ functools.partial(_place_region_labels, ctx, child, region_items, log_x=log_x)
1750
+ )
1751
+ if idx_f == 0 and callout_items:
1752
+ ctx.finishers.append(functools.partial(_place_callouts, ctx, child, callout_items))
1753
+ return frames
1754
+
1755
+ series_spec: Any
1756
+ if single:
1757
+ series_spec = None if "" in reps else data[""]
1758
+ else:
1759
+ series_spec = {k: v for k, v in data.items() if k not in reps} or None
1760
+ spec = _base_spec(
1761
+ title,
1762
+ label,
1763
+ unit,
1764
+ x=[
1765
+ (int(v) if float(v) == int(v) else float(v))
1766
+ if _is_number(v)
1767
+ else (v if isinstance(v, str) else _jsonable(v))
1768
+ for v in x
1769
+ ],
1770
+ series=_jsonable(series_spec),
1771
+ x_label=x_label,
1772
+ x_unit=x_unit_given,
1773
+ highlight=hl or None,
1774
+ baseline=base,
1775
+ facet=facet or None,
1776
+ band=band_spec or None,
1777
+ band_label=band_label,
1778
+ points={k: [r.tolist() for r in v] for k, v in reps.items()} or None,
1779
+ points_label=points_label,
1780
+ events={str(_jsonable(k)): str(v) for k, v in (events or {}).items()} or None,
1781
+ regions=regions_spec or None,
1782
+ callouts=callouts_spec or None,
1783
+ reference=list(ref) if ref else None,
1784
+ zero=zero or None,
1785
+ log=log or None,
1786
+ log_x=log_x or None,
1787
+ fit=fit if fit else None,
1788
+ end_values=None if end_values else False,
1789
+ fmt=fmt,
1790
+ )
1791
+ dot_label = (points_label or "").strip() or "replicates"
1792
+ fit_note = (
1793
+ f"dashed: { {'linear': 'linear fit', 'log': 'log-linear fit', 'power': 'power-law fit'}[fit_mode] }"
1794
+ if fit_mode is not None
1795
+ else None
1796
+ )
1797
+ notes = [
1798
+ nt
1799
+ for nt in (
1800
+ f"band: {band_label}" if bands and band_label else None,
1801
+ f"dots: {dot_label}" if reps else None,
1802
+ fit_note,
1803
+ )
1804
+ if nt
1805
+ ]
1806
+
1807
+ if facet:
1808
+
1809
+ def _facet_height(
1810
+ cell_width_mm: float, _m: _Measure, _s: _Sizes, _t: Theme = MINTFIG_THEME
1811
+ ) -> float:
1812
+ nrows, _ = _facet_grid(cell_width_mm)
1813
+ return nrows * 27.0 + (nrows - 1) * 4.5 + (4.0 if x_label else 0.0)
1814
+
1815
+ return Panel(
1816
+ kind="trend",
1817
+ title=title,
1818
+ label=label,
1819
+ unit=unit,
1820
+ spec=spec,
1821
+ facts=facts,
1822
+ describe=describe,
1823
+ issues=issues,
1824
+ _height_mm=_facet_height,
1825
+ _min_height_mm=lambda w, _m, _s, _t: (
1826
+ _facet_grid(w)[0] * 22.0 + (_facet_grid(w)[0] - 1) * 4.5 + (4.0 if x_label else 0.0)
1827
+ ),
1828
+ _draw=lambda _ctx, _ax: None,
1829
+ _frames=_facet_frames,
1830
+ measure_note="; ".join(notes) or None,
1831
+ alt_facts=alt_facts,
1832
+ )
1833
+
1834
+ return Panel(
1835
+ kind="trend",
1836
+ title=title,
1837
+ label=label,
1838
+ unit=unit,
1839
+ spec=spec,
1840
+ facts=facts,
1841
+ describe=describe,
1842
+ issues=issues,
1843
+ _height_mm=lambda w, _m, _s, _t: min(54.0, max(36.0, 0.40 * w)) + (4.0 if x_label else 0.0),
1844
+ _min_height_mm=lambda _w, _m, _s, _t: 30.0 + (4.0 if x_label else 0.0),
1845
+ stretch=True,
1846
+ _draw=_draw,
1847
+ measure_note="; ".join(notes) or None,
1848
+ alt_facts=alt_facts,
1849
+ color_items=tuple(nm for nm in names if nm),
1850
+ color_focus=tuple(nm for nm in focus if nm),
1851
+ color_mode="highlight" if hl else "series",
1852
+ uses_default="" in colored,
1853
+ color_baseline=base,
1854
+ )
1855
+
1856
+
1857
+ def _place_event_labels(ctx: _Ctx, ax: Axes, events: Sequence[Any], avoid: Sequence[Any]) -> None:
1858
+ """Move each event label to a spot where it covers no line, marker or other label.
1859
+
1860
+ Tries the top of the rule on its preferred side, then the other side, then just
1861
+ under the top gridline, then the bottom of the plot. When every spot is taken the
1862
+ first is kept and an ``event_label_collides`` warning says to shorten the label.
1863
+ """
1864
+ if not events:
1865
+ return
1866
+ renderer = ctx.fig.canvas.get_renderer()
1867
+ frame = ax.get_window_extent(renderer)
1868
+ rules = [rule for _note, rule, _pos, _text, _right in events]
1869
+ paths = _data_paths(ax, rules)
1870
+ taken = [
1871
+ t.get_window_extent(renderer)
1872
+ for t in [*avoid, *ctx.fig.texts]
1873
+ if t is not None and t.get_visible() and t.get_text()
1874
+ ]
1875
+ taken += [box for axis in (ax.xaxis, ax.yaxis) for _, box in _tick_label_boxes(axis, renderer)]
1876
+ # A label may reach left over the empty top of the y-tick gutter, never past it.
1877
+ gutter = ax.yaxis.get_tightbbox(renderer)
1878
+ left_limit = min(frame.x0, gutter.x0) if gutter is not None else frame.x0
1879
+ y0, y1 = ax.get_ylim()
1880
+ ticks = [float(t) for t in ax.yaxis.get_majorticklocs() if min(y0, y1) < t < max(y0, y1)]
1881
+ upper = sorted(ticks, reverse=y1 > y0)
1882
+ frac_top = None
1883
+ if upper:
1884
+ top_tick = upper[0]
1885
+ display = ax.transData.transform((ax.get_xlim()[0], top_tick))
1886
+ frac_top = float(ax.transAxes.inverted().transform(display)[1])
1887
+ for note, _rule, pos, text, near_right in events:
1888
+ sides = [near_right, not near_right]
1889
+ spots: list[tuple[float, str, bool | None]] = [(1.0, "top", side) for side in sides]
1890
+ if frac_top is not None and 0.2 < frac_top < 0.98:
1891
+ spots += [(frac_top, "top", side) for side in sides]
1892
+ spots += [(0.0, "bottom", side) for side in sides]
1893
+ # Intermediate vertical spots along the event rule (for narrow panels / wider Linux fonts)
1894
+ for mid_frac in (0.75, 0.50, 0.25):
1895
+ spots += [(mid_frac, "center", side) for side in sides]
1896
+ # Straddling the top tip of the rule, then just above the plot frame.
1897
+ spots += [(1.0, "center", side) for side in sides]
1898
+ spots += [(1.0, "above", side) for side in sides]
1899
+ chosen = None
1900
+ for frac, va, right in spots:
1901
+ note.xy = (pos, frac)
1902
+ note.set_verticalalignment("bottom" if va == "above" else va)
1903
+ note.set_horizontalalignment("right" if right else "left")
1904
+ dx_pt = -3.0 if right else 3.0
1905
+ dy = -2.0 if va == "top" else (2.0 if va == "bottom" else (0.0 if va == "center" else 1.0))
1906
+ note.set_position((dx_pt, dy))
1907
+ box = note.get_window_extent(renderer).expanded(1.0, 1.0)
1908
+ inside = box.x0 >= left_limit - 1 and box.x1 <= frame.x1 + 1
1909
+ if va == "above":
1910
+ inside = inside and box.y1 <= ctx.fig.bbox.y1
1911
+ clear = not any(box.overlaps(other) for other in taken)
1912
+ free = not any(path.intersects_bbox(box, filled=False) for path in paths)
1913
+ if inside and clear and free:
1914
+ chosen = box
1915
+ break
1916
+ if chosen is None:
1917
+ frac, va, right = spots[0]
1918
+ note.xy = (pos, frac)
1919
+ note.set_verticalalignment(va)
1920
+ note.set_horizontalalignment("right" if right else "left")
1921
+ note.set_position((-3.0 if right else 3.0, -2.0))
1922
+ chosen = note.get_window_extent(renderer)
1923
+ ctx.issues.append(
1924
+ _issue(
1925
+ "event_label_collides",
1926
+ "warning",
1927
+ f"The event label {text!r} covers a line or another label wherever it is "
1928
+ "placed in this panel.",
1929
+ "Shorten the event label (one or two words, e.g. 'v2.3'), move the detail "
1930
+ 'to note=, or give the panel a full-width row with layout=[["a"], ["b"]].',
1931
+ panel=ctx.key,
1932
+ )
1933
+ )
1934
+ taken.append(chosen)
1935
+
1936
+
1937
+ def _reference_in_margin(
1938
+ ctx: _Ctx,
1939
+ ax: Axes,
1940
+ note: Any,
1941
+ text: str,
1942
+ y_value: float,
1943
+ avoid: Sequence[Any],
1944
+ taken: Sequence[Bbox],
1945
+ paths: Sequence[Any],
1946
+ ) -> bool:
1947
+ """Put a reference label in the end-label column right of the plot, beside the line.
1948
+
1949
+ The column is as wide as the end labels already make it (the panel's cell is
1950
+ sized to them), so the label never reaches into a neighbouring panel. Returns
1951
+ False, leaving ``note`` to the caller, when no spot there is free.
1952
+ """
1953
+ renderer = ctx.fig.canvas.get_renderer()
1954
+ frame = ax.get_window_extent(renderer)
1955
+ ends = [
1956
+ t.get_window_extent(renderer).x1
1957
+ for t in avoid
1958
+ if t is not None and t.get_visible() and t.get_text()
1959
+ ]
1960
+ col_right = max([frame.x1, *ends])
1961
+ k = ctx.pt_per_px
1962
+ dx = 6.0
1963
+ # Allow a few pt into the inter-panel gutter (never past the figure edge) so
1964
+ # wrapped margin labels stay legible under slightly wider Linux fallback fonts.
1965
+ max_right = min(col_right + 4.0 / k, ctx.fig.bbox.x1 - 2.0 / k)
1966
+ room_pt = (max_right - frame.x1) * k - dx
1967
+ if room_pt <= 0:
1968
+ return False
1969
+ size = float(note.get_fontsize())
1970
+ shown = [text]
1971
+ wrapped = ctx.measure.wrap(text, room_pt, size)
1972
+ if len(wrapped) == 2:
1973
+ shown.append("\n".join(wrapped))
1974
+ elif "-" in text and len(wrapped) == 1:
1975
+ parts = text.split("-", 1)
1976
+ if parts[0] and parts[1]:
1977
+ shown.append(f"{parts[0]}-\n{parts[1]}")
1978
+ for candidate in shown:
1979
+ note.set_text(_plain(candidate, ctx.theme))
1980
+ note.xy = (1.0, y_value)
1981
+ note.set_horizontalalignment("left")
1982
+ for va, dy in (("center", 0.0), ("bottom", 1.5), ("top", -1.5)):
1983
+ note.set_verticalalignment(va)
1984
+ note.set_position((dx, dy))
1985
+ box = note.get_window_extent(renderer)
1986
+ inside = (
1987
+ box.x1 <= max_right + 1
1988
+ and box.y0 >= frame.y0 - 1
1989
+ and box.y1 <= frame.y1 + 0.5 * ctx.sizes.small / k
1990
+ )
1991
+ clear = not any(box.overlaps(other) for other in taken)
1992
+ free = not any(path.intersects_bbox(box, filled=False) for path in paths)
1993
+ if inside and clear and free:
1994
+ return True
1995
+ return False
1996
+
1997
+
1998
+ def _place_reference_label(ctx: _Ctx, ax: Axes, ref: Any, avoid: Sequence[Any]) -> None:
1999
+ """Move a reference-line label to a spot where it covers no line, marker or label.
2000
+
2001
+ ``ref`` is ``(note, line, text, prefer_right)``. Tries the preferred end above the
2002
+ line, the other end above it, both ends below it, then the middle, one third and
2003
+ two thirds along it (above, then below). Dense lines (daily data) leave none of
2004
+ those free: the label then goes in the right margin beside the line's end, in the
2005
+ column the end labels use (on one line or wrapped onto two), if that is free of
2006
+ them. Only when that fails too is the first spot kept and a
2007
+ ``reference_label_collides`` warning says what to change.
2008
+ """
2009
+ if ref is None:
2010
+ return
2011
+ note, line, text, prefer_right = ref
2012
+ renderer = ctx.fig.canvas.get_renderer()
2013
+ frame = ax.get_window_extent(renderer)
2014
+ paths = _data_paths(ax, [line])
2015
+ taken = [
2016
+ t.get_window_extent(renderer)
2017
+ for t in [*avoid, *ax.texts, *ctx.fig.texts]
2018
+ if t is not None and t is not note and t.get_visible() and t.get_text()
2019
+ ]
2020
+ taken += [box for axis in (ax.xaxis, ax.yaxis) for _, box in _tick_label_boxes(axis, renderer)]
2021
+ # Spots as (x as a fraction of the axes, above the line?): the ends first, then
2022
+ # inside the span, where a crowded narrow panel often still has room.
2023
+ ends = [1.0 if prefer_right else 0.0, 0.0 if prefer_right else 1.0]
2024
+ spots = [(at, above) for above in (True, False) for at in ends]
2025
+ spots += [(at, above) for at in (0.5, 1 / 3, 2 / 3, 0.2, 0.8) for above in (True, False)]
2026
+ y_value = note.xy[1]
2027
+
2028
+ def _put(at: float, above: bool, dy_mag: float = 2.5) -> None:
2029
+ note.xy = (at, y_value)
2030
+ note.set_horizontalalignment("right" if at == 1.0 else "left" if at == 0.0 else "center")
2031
+ note.set_verticalalignment("bottom" if above else "top")
2032
+ dx = -2.0 if at == 1.0 else 2.0 if at == 0.0 else 0.0
2033
+ note.set_position((dx, dy_mag if above else -dy_mag))
2034
+
2035
+ for dy_mag in (2.5, 4.5):
2036
+ for at, above in spots:
2037
+ _put(at, above, dy_mag)
2038
+ box = note.get_window_extent(renderer)
2039
+ inside = (
2040
+ box.x0 >= frame.x0 - 1
2041
+ and box.x1 <= frame.x1 + 1
2042
+ and box.y0 >= frame.y0 - 1
2043
+ and box.y1 <= frame.y1 + 1
2044
+ )
2045
+ clear = not any(box.overlaps(other) for other in taken)
2046
+ free = not any(path.intersects_bbox(box, filled=False) for path in paths)
2047
+ if inside and clear and free:
2048
+ return
2049
+ if _reference_in_margin(ctx, ax, note, text, y_value, avoid, taken, paths):
2050
+ return
2051
+ note.set_text(_plain(text, ctx.theme))
2052
+ _put(spots[0][0], True)
2053
+ ctx.issues.append(
2054
+ _issue(
2055
+ "reference_label_collides",
2056
+ "warning",
2057
+ f"The reference label {text!r} covers a line or another label wherever it is "
2058
+ "placed in this panel.",
2059
+ "Shorten the reference label to one or two words, or pass the reference as a "
2060
+ 'bare number (reference=1.0) and name the line in note= ("dashed line: ...").',
2061
+ panel=ctx.key,
2062
+ )
2063
+ )
2064
+
2065
+
2066
+ def _reorder_band(band: Any, order: np.ndarray, n: int) -> Any:
2067
+ """Apply the x sort to a band given in any accepted form (numbers stay as they are)."""
2068
+
2069
+ def _one(entry: Any) -> Any:
2070
+ if _is_number(entry):
2071
+ return entry
2072
+ try:
2073
+ arr = np.asarray(
2074
+ [[np.nan if v is None else float(v) for v in part] for part in entry]
2075
+ if not isinstance(entry, np.ndarray)
2076
+ else entry,
2077
+ dtype=float,
2078
+ )
2079
+ except (TypeError, ValueError):
2080
+ try:
2081
+ arr = np.asarray([np.nan if v is None else float(v) for v in entry], dtype=float)
2082
+ except (TypeError, ValueError):
2083
+ return entry # reported by _trend_bands
2084
+ if arr.ndim == 2 and arr.shape == (2, n):
2085
+ return arr[:, order]
2086
+ if arr.ndim == 1 and arr.size == n:
2087
+ return arr[order]
2088
+ return entry
2089
+
2090
+ if _has_items(band) and not _is_one_dimensional(band):
2091
+ return {k: _one(v) for k, v in _pairs(band)}
2092
+ return _one(band)
2093
+
2094
+
2095
+ MAX_CALLOUTS = 4
2096
+
2097
+
2098
+ def _parse_x_point(val: Any, x_kind: str, x_text: Sequence[str], what: str) -> float:
2099
+ """Parse a single x coordinate for events, regions, or callouts on trend()."""
2100
+ if x_kind == "number":
2101
+ try:
2102
+ pos = _to_float(float(val) if isinstance(val, str) else val, what)
2103
+ except ValueError as exc:
2104
+ raise ExplainError(
2105
+ f"{what} {val!r} is not a number on this numeric x axis.",
2106
+ fix_hint="Use a numeric x value matching the x axis.",
2107
+ ) from exc
2108
+ if not math.isfinite(pos):
2109
+ raise ExplainError(
2110
+ f"{what} {val!r} must be finite.",
2111
+ fix_hint="Use a finite numeric x value.",
2112
+ )
2113
+ return pos
2114
+ if x_kind == "date":
2115
+ try:
2116
+ pos = float(mdates.date2num(np.datetime64(val)))
2117
+ except (ValueError, TypeError) as exc:
2118
+ raise ExplainError(
2119
+ f"{what} {val!r} is not a valid date.",
2120
+ fix_hint="Use an ISO date such as '2026-03-01' or a date/datetime object.",
2121
+ ) from exc
2122
+ return pos
2123
+ if str(val) not in x_text:
2124
+ raise ExplainError(
2125
+ f"{what} {val!r} is not one of the x labels.",
2126
+ fix_hint="Use an x value exactly as it appears in x.",
2127
+ )
2128
+ return float(x_text.index(str(val)))
2129
+
2130
+
2131
+ def _parse_trend_regions(
2132
+ regions: Sequence[tuple[Any, Any, str]] | None,
2133
+ x_kind: str,
2134
+ x_text: Sequence[str],
2135
+ *,
2136
+ log_x: bool,
2137
+ ) -> tuple[list[tuple[float, float, str]], list[list[Any]]]:
2138
+ """Validate ``trend(regions=[(x0, x1, label), ...])``."""
2139
+ if regions is None:
2140
+ return [], []
2141
+ if isinstance(regions, (str, bytes, Mapping)) or not isinstance(regions, Sequence):
2142
+ raise ExplainError(
2143
+ f"trend(regions) must be a list of (x0, x1, label) tuples, got {type(regions).__name__}.",
2144
+ fix_hint='e.g. regions=[(2, 5, "warmup")] or regions=[("2026-01-01", "2026-03-01", "Q1")].',
2145
+ )
2146
+ parsed: list[tuple[float, float, str]] = []
2147
+ spec_out: list[list[Any]] = []
2148
+ for idx, item in enumerate(regions):
2149
+ if isinstance(item, (str, bytes, Mapping)) or not isinstance(item, Sequence) or len(item) != 3:
2150
+ raise ExplainError(
2151
+ f"trend(regions[{idx}]) must be a (x0, x1, label) 3-tuple, got {item!r}.",
2152
+ fix_hint='Pass (x0, x1, "short label") for each shaded region.',
2153
+ )
2154
+ raw0, raw1, label = item
2155
+ p0 = _parse_x_point(raw0, x_kind, x_text, f"trend(regions[{idx}]) start")
2156
+ p1 = _parse_x_point(raw1, x_kind, x_text, f"trend(regions[{idx}]) end")
2157
+ if p0 >= p1:
2158
+ raise ExplainError(
2159
+ f"trend(regions[{idx}]) start {raw0!r} must be strictly less than end {raw1!r}.",
2160
+ fix_hint="Order each region tuple as (x0, x1, label) with x0 < x1.",
2161
+ )
2162
+ if log_x and p0 <= 0:
2163
+ raise ExplainError(
2164
+ f"trend(regions[{idx}]) requires positive x bounds on a log_x axis.",
2165
+ fix_hint="Use positive x0 and x1 values when log_x=True.",
2166
+ )
2167
+ text = str(label).strip()
2168
+ parsed.append((p0, p1, text))
2169
+ spec_out.append([_jsonable(raw0), _jsonable(raw1), text])
2170
+ return parsed, spec_out
2171
+
2172
+
2173
+ def _parse_trend_callouts(
2174
+ callouts: Sequence[tuple[Any, float, str]] | None,
2175
+ x_kind: str,
2176
+ x_text: Sequence[str],
2177
+ *,
2178
+ log_x: bool,
2179
+ log_y: bool,
2180
+ ) -> tuple[list[tuple[float, float, str]], list[list[Any]]]:
2181
+ """Validate ``trend(callouts=[(x, y, note), ...])`` (max 4)."""
2182
+ if callouts is None:
2183
+ return [], []
2184
+ if isinstance(callouts, (str, bytes, Mapping)) or not isinstance(callouts, Sequence):
2185
+ raise ExplainError(
2186
+ f"trend(callouts) must be a list of (x, y, note) tuples, got {type(callouts).__name__}.",
2187
+ fix_hint='e.g. callouts=[(5, 1200, "peak load")].',
2188
+ )
2189
+ if len(callouts) > MAX_CALLOUTS:
2190
+ raise ExplainError(
2191
+ f"trend(callouts) got {len(callouts)} callouts; at most {MAX_CALLOUTS} stay legible.",
2192
+ fix_hint=f"Keep at most {MAX_CALLOUTS} callouts for the most important points.",
2193
+ )
2194
+ parsed: list[tuple[float, float, str]] = []
2195
+ spec_out: list[list[Any]] = []
2196
+ for idx, item in enumerate(callouts):
2197
+ if isinstance(item, (str, bytes, Mapping)) or not isinstance(item, Sequence) or len(item) != 3:
2198
+ raise ExplainError(
2199
+ f"trend(callouts[{idx}]) must be an (x, y, note) 3-tuple, got {item!r}.",
2200
+ fix_hint='Pass (x, y, "short note") for each callout.',
2201
+ )
2202
+ raw_x, raw_y, note = item
2203
+ px = _parse_x_point(raw_x, x_kind, x_text, f"trend(callouts[{idx}]) x")
2204
+ py = _to_float(raw_y, f"trend(callouts[{idx}]) y")
2205
+ if not math.isfinite(py):
2206
+ raise ExplainError(
2207
+ f"trend(callouts[{idx}]) y={raw_y!r} must be finite.",
2208
+ fix_hint="Pass a finite numeric y coordinate for the callout anchor.",
2209
+ )
2210
+ if log_x and px <= 0:
2211
+ raise ExplainError(
2212
+ f"trend(callouts[{idx}]) x must be positive on a log_x axis.",
2213
+ fix_hint="Use positive x values when log_x=True.",
2214
+ )
2215
+ if log_y and py <= 0:
2216
+ raise ExplainError(
2217
+ f"trend(callouts[{idx}]) y must be positive on a log y axis.",
2218
+ fix_hint="Use positive y values when log=True.",
2219
+ )
2220
+ text = str(note).strip()
2221
+ if not text:
2222
+ raise ExplainError(
2223
+ f"trend(callouts[{idx}]) has an empty note.",
2224
+ fix_hint='Pass a short descriptive note, e.g. (5, 1200, "v2.3 regression").',
2225
+ )
2226
+ parsed.append((px, py, text))
2227
+ spec_out.append([_jsonable(raw_x), float(py), text])
2228
+ return parsed, spec_out
2229
+
2230
+
2231
+ def _visible_text_boxes(ctx: _Ctx, exclude: Any = None) -> list[Bbox]:
2232
+ """Window bounding boxes of all visible non-empty Text artists on the figure."""
2233
+ from matplotlib.text import Text
2234
+
2235
+ renderer = ctx.fig.canvas.get_renderer()
2236
+ return [
2237
+ t.get_window_extent(renderer)
2238
+ for t in ctx.fig.findobj(Text)
2239
+ if t is not exclude and t.get_visible() and t.get_text().strip() and t.get_alpha() != 0
2240
+ ]
2241
+
2242
+
2243
+ def _audit_line_paths(ax: Axes) -> list[Any]:
2244
+ """Display-space paths of visible non-grid lines on ``ax`` (matching audit_figure)."""
2245
+ grid = {id(g) for g in (*ax.get_xgridlines(), *ax.get_ygridlines())}
2246
+ return [
2247
+ ln.get_transform().transform_path(ln.get_path())
2248
+ for ln in ax.lines
2249
+ if id(ln) not in grid
2250
+ and ln.get_visible()
2251
+ and len(ln.get_xdata()) >= 2
2252
+ and ln.get_linestyle() not in ("None", "", " ")
2253
+ and ln.get_linewidth() > 0
2254
+ ]
2255
+
2256
+
2257
+ def _pad_bbox(bb: Bbox, pad: float = 1.5) -> Bbox:
2258
+ return Bbox.from_extents(bb.x0 - pad, bb.y0 - pad, bb.x1 + pad, bb.y1 + pad)
2259
+
2260
+
2261
+ def _place_region_labels(
2262
+ ctx: _Ctx,
2263
+ ax: Axes,
2264
+ regions: Sequence[tuple[float, float, str]],
2265
+ *,
2266
+ log_x: bool = False,
2267
+ ) -> None:
2268
+ """Place muted top labels centered inside shaded regions, avoiding lines and text."""
2269
+ sz = ctx.sizes
2270
+ theme = ctx.theme
2271
+ renderer = ctx.fig.canvas.get_renderer()
2272
+ frame = ax.get_window_extent(renderer)
2273
+ fig_box = ctx.fig.bbox
2274
+ paths = _audit_line_paths(ax)
2275
+ taken = _visible_text_boxes(ctx)
2276
+ x_lo, x_hi = sorted(ax.get_xlim())
2277
+ for r0, r1, text in regions:
2278
+ if not text:
2279
+ continue
2280
+ vis0 = max(r0, x_lo)
2281
+ vis1 = min(r1, x_hi)
2282
+ if vis0 >= vis1:
2283
+ vis0, vis1 = r0, r1
2284
+ mid_x = math.sqrt(vis0 * vis1) if (log_x and vis0 > 0 and vis1 > 0) else 0.5 * (vis0 + vis1)
2285
+ note = ax.annotate(
2286
+ _plain(text, theme),
2287
+ (mid_x, 1.0),
2288
+ xycoords=("data", "axes fraction"),
2289
+ xytext=(0.0, -3.0),
2290
+ textcoords="offset points",
2291
+ ha="center",
2292
+ va="top",
2293
+ fontsize=sz.small,
2294
+ color=theme.muted,
2295
+ zorder=6,
2296
+ bbox=ctx.halo_bbox(0.08, alpha=0.82),
2297
+ annotation_clip=False,
2298
+ )
2299
+ cands = [
2300
+ (mid_x, 1.0, "center", "top", 0.0, -3.0, True),
2301
+ (mid_x, 0.88, "center", "top", 0.0, 0.0, True),
2302
+ (mid_x, 0.0, "center", "bottom", 0.0, 3.0, True),
2303
+ (vis0, 1.0, "left", "top", 3.0, -3.0, True),
2304
+ (vis1, 1.0, "right", "top", -3.0, -3.0, True),
2305
+ (vis0, 0.0, "left", "bottom", 3.0, 3.0, True),
2306
+ (vis1, 0.0, "right", "bottom", -3.0, 3.0, True),
2307
+ (mid_x, 0.72, "center", "top", 0.0, 0.0, True),
2308
+ (mid_x, 0.50, "center", "center", 0.0, 0.0, True),
2309
+ (mid_x, 0.25, "center", "bottom", 0.0, 0.0, True),
2310
+ (mid_x, 1.0, "center", "bottom", 0.0, 2.5, False),
2311
+ ]
2312
+ best = cands[0]
2313
+ best_score = (999, 999, 999, 999)
2314
+ for cx, yfrac, ha, va, dx, dy, inside_pref in cands:
2315
+ note.xy = (cx, yfrac)
2316
+ note.set_ha(ha)
2317
+ note.set_va(va)
2318
+ note.set_position((dx, dy))
2319
+ bb = note.get_window_extent(renderer)
2320
+ pbb = _pad_bbox(bb, 1.5)
2321
+ out_fig = int(
2322
+ not (
2323
+ bb.x0 >= fig_box.x0 + 2
2324
+ and bb.x1 <= fig_box.x1 - 2
2325
+ and bb.y0 >= fig_box.y0 + 2
2326
+ and bb.y1 <= fig_box.y1 - 2
2327
+ )
2328
+ )
2329
+ out_frame = int(
2330
+ not (
2331
+ bb.x0 >= frame.x0 - 2
2332
+ and bb.x1 <= frame.x1 + 2
2333
+ and bb.y0 >= frame.y0 - 2
2334
+ and bb.y1 <= frame.y1 + 2
2335
+ )
2336
+ )
2337
+ n_line = sum(1 for p in paths if p.intersects_bbox(bb, filled=False))
2338
+ n_text = sum(1 for tb in taken if pbb.overlaps(tb))
2339
+ score = (out_fig, n_line, n_text, out_frame if inside_pref else out_frame + 1)
2340
+ if score < best_score:
2341
+ best_score = score
2342
+ best = (cx, yfrac, ha, va, dx, dy, inside_pref)
2343
+ if score == (0, 0, 0, 0):
2344
+ break
2345
+ note.xy = (best[0], best[1])
2346
+ note.set_ha(best[2])
2347
+ note.set_va(best[3])
2348
+ note.set_position((best[4], best[5]))
2349
+ taken.append(note.get_window_extent(renderer))
2350
+
2351
+
2352
+ def _callout_arrow_segment(
2353
+ ax_px: float, ay_px: float, bb: Bbox
2354
+ ) -> tuple[float, float, Any | None]:
2355
+ """Return ``(start_x_px, start_y_px, trimmed_path)`` from nearest edge of ``bb`` to anchor."""
2356
+ from matplotlib.path import Path as MplPath
2357
+
2358
+ px = min(max(ax_px, bb.x0), bb.x1)
2359
+ py = min(max(ay_px, bb.y0), bb.y1)
2360
+ vx, vy = ax_px - px, ay_px - py
2361
+ seg_len = math.hypot(vx, vy)
2362
+ if seg_len < 7.0:
2363
+ return px, py, None
2364
+ t0 = min(0.35, 3.0 / seg_len)
2365
+ t1 = max(t0 + 0.05, 1.0 - 7.5 / seg_len)
2366
+ s0 = (px + t0 * vx, py + t0 * vy)
2367
+ s1 = (px + t1 * vx, py + t1 * vy)
2368
+ return px, py, MplPath([s0, s1])
2369
+
2370
+
2371
+ def _two_line_wrap(text: str) -> str | None:
2372
+ """Split a multi-word callout near its middle onto two lines; None for single words."""
2373
+ words = text.split()
2374
+ if len(words) < 2 or "\n" in text:
2375
+ return None
2376
+ best_i = min(
2377
+ range(1, len(words)),
2378
+ key=lambda i: abs(len(" ".join(words[:i])) - len(" ".join(words[i:]))),
2379
+ )
2380
+ return " ".join(words[:best_i]) + "\n" + " ".join(words[best_i:])
2381
+
2382
+
2383
+ def _place_callouts(
2384
+ ctx: _Ctx,
2385
+ ax: Axes,
2386
+ callouts: Sequence[tuple[float, float, str]],
2387
+ ) -> None:
2388
+ """Place direct callout annotations with leader arrows, avoiding lines, text, and arrow crossings."""
2389
+ sz = ctx.sizes
2390
+ theme = ctx.theme
2391
+ renderer = ctx.fig.canvas.get_renderer()
2392
+ frame = ax.get_window_extent(renderer)
2393
+ fig_box = ctx.fig.bbox
2394
+ paths = _audit_line_paths(ax)
2395
+ taken = _visible_text_boxes(ctx)
2396
+ k = ctx.pt_per_px
2397
+ arrow_kw = {
2398
+ "arrowstyle": "-|>,head_length=0.35,head_width=0.2",
2399
+ "color": theme.muted,
2400
+ "linewidth": 0.75 * sz.scale,
2401
+ "shrinkA": 2.0,
2402
+ "shrinkB": 3.5,
2403
+ }
2404
+ base_offsets = [
2405
+ # Tier 1: short clean offsets
2406
+ (12.0, 14.0, "left", "bottom"),
2407
+ (-12.0, 14.0, "right", "bottom"),
2408
+ (12.0, -14.0, "left", "top"),
2409
+ (-12.0, -14.0, "right", "top"),
2410
+ (0.0, 18.0, "center", "bottom"),
2411
+ (0.0, -18.0, "center", "top"),
2412
+ (18.0, 0.0, "left", "center"),
2413
+ (-18.0, 0.0, "right", "center"),
2414
+ # Tier 2: medium & shifted-center offsets
2415
+ (20.0, 22.0, "left", "bottom"),
2416
+ (-20.0, 22.0, "right", "bottom"),
2417
+ (20.0, -22.0, "left", "top"),
2418
+ (-20.0, -22.0, "right", "top"),
2419
+ (14.0, -22.0, "center", "top"),
2420
+ (-14.0, -22.0, "center", "top"),
2421
+ (14.0, 22.0, "center", "bottom"),
2422
+ (-14.0, 22.0, "center", "bottom"),
2423
+ (0.0, 28.0, "center", "bottom"),
2424
+ (0.0, -28.0, "center", "top"),
2425
+ (28.0, 10.0, "left", "bottom"),
2426
+ (-28.0, 10.0, "right", "bottom"),
2427
+ (28.0, -10.0, "left", "top"),
2428
+ (-28.0, -10.0, "right", "top"),
2429
+ # Tier 3: wider fallback offsets
2430
+ (0.0, 42.0, "center", "bottom"),
2431
+ (0.0, -42.0, "center", "top"),
2432
+ (32.0, 34.0, "left", "bottom"),
2433
+ (-32.0, 34.0, "right", "bottom"),
2434
+ (32.0, -34.0, "left", "top"),
2435
+ (-32.0, -34.0, "right", "top"),
2436
+ (44.0, 0.0, "left", "center"),
2437
+ (-44.0, 0.0, "right", "center"),
2438
+ (0.0, 56.0, "center", "bottom"),
2439
+ (0.0, -56.0, "center", "top"),
2440
+ ]
2441
+ for cx, cy, text in callouts:
2442
+ disp = ax.transData.transform((cx, cy))
2443
+ ax_px, ay_px = float(disp[0]), float(disp[1])
2444
+ fx, fy = ax.transAxes.inverted().transform(disp)
2445
+ note = ax.annotate(
2446
+ _plain(text, theme),
2447
+ xy=(cx, cy),
2448
+ xycoords="data",
2449
+ xytext=(12.0, 14.0),
2450
+ textcoords="offset points",
2451
+ ha="left",
2452
+ va="bottom",
2453
+ fontsize=sz.small,
2454
+ color=theme.ink,
2455
+ zorder=7,
2456
+ bbox=ctx.halo_bbox(0.16, alpha=0.92),
2457
+ annotation_clip=False,
2458
+ )
2459
+ # Prefer pointing inward away from the nearest plot edges.
2460
+ prefer_dx = -1.0 if fx > 0.55 else 1.0
2461
+ prefer_dy = -1.0 if fy > 0.60 else 1.0
2462
+ ordered = sorted(
2463
+ base_offsets,
2464
+ key=lambda c: (
2465
+ int(math.hypot(c[0], c[1]) // 18),
2466
+ 0 if c[0] * prefer_dx >= 0 else 1,
2467
+ 0 if c[1] * prefer_dy >= 0 else 1,
2468
+ math.hypot(c[0], c[1]),
2469
+ ),
2470
+ )
2471
+ text_variants = [text]
2472
+ wrapped = _two_line_wrap(text)
2473
+ if wrapped is not None:
2474
+ text_variants.append(wrapped)
2475
+
2476
+ best_variant = text
2477
+ best = ordered[0]
2478
+ best_score: tuple[int, int, int, int, int, int, int, float] = (
2479
+ 999,
2480
+ 999,
2481
+ 999,
2482
+ 999,
2483
+ 999,
2484
+ 999,
2485
+ 999,
2486
+ 1e9,
2487
+ )
2488
+ for v_idx, variant in enumerate(text_variants):
2489
+ note.set_text(_plain(variant, theme))
2490
+ for dx, dy, ha, va in ordered:
2491
+ note.set_position((dx, dy))
2492
+ note.set_ha(ha)
2493
+ note.set_va(va)
2494
+ bb = note.get_window_extent(renderer)
2495
+ pbb = _pad_bbox(bb, 1.5)
2496
+ out_fig = int(
2497
+ not (
2498
+ bb.x0 >= fig_box.x0 + 3
2499
+ and bb.x1 <= fig_box.x1 - 3
2500
+ and bb.y0 >= fig_box.y0 + 3
2501
+ and bb.y1 <= fig_box.y1 - 3
2502
+ )
2503
+ )
2504
+ out_frame = int(
2505
+ not (
2506
+ bb.x0 >= frame.x0 + 1
2507
+ and bb.x1 <= frame.x1 - 1
2508
+ and bb.y0 >= frame.y0 + 3.5
2509
+ and bb.y1 <= frame.y1 - 1
2510
+ )
2511
+ )
2512
+ n_line = sum(1 for p in paths if p.intersects_bbox(bb, filled=False))
2513
+ n_text = sum(1 for tb in taken if pbb.overlaps(tb))
2514
+ _, _, seg_path = _callout_arrow_segment(ax_px, ay_px, bb)
2515
+ if seg_path is not None:
2516
+ n_arrow_text = sum(
2517
+ 1 for tb in taken if seg_path.intersects_bbox(_pad_bbox(tb, 1.0), filled=True)
2518
+ )
2519
+ n_arrow_line = sum(1 for p in paths if seg_path.intersects_path(p, filled=False))
2520
+ else:
2521
+ n_arrow_text = 0
2522
+ n_arrow_line = 0
2523
+ score = (
2524
+ out_fig,
2525
+ n_line,
2526
+ n_text,
2527
+ n_arrow_text,
2528
+ n_arrow_line,
2529
+ out_frame,
2530
+ v_idx,
2531
+ math.hypot(dx, dy),
2532
+ )
2533
+ if score < best_score:
2534
+ best_score = score
2535
+ best = (dx, dy, ha, va)
2536
+ best_variant = variant
2537
+ if score[:6] == (0, 0, 0, 0, 0, 0):
2538
+ break
2539
+ if best_score[:6] == (0, 0, 0, 0, 0, 0):
2540
+ break
2541
+ note.set_text(_plain(best_variant, theme))
2542
+ note.set_position((best[0], best[1]))
2543
+ note.set_ha(best[2])
2544
+ note.set_va(best[3])
2545
+ final_bb = note.get_window_extent(renderer)
2546
+ start_px, start_py, _ = _callout_arrow_segment(ax_px, ay_px, final_bb)
2547
+ ax.annotate(
2548
+ "",
2549
+ xy=(cx, cy),
2550
+ xycoords="data",
2551
+ xytext=((start_px - ax_px) * k, (start_py - ay_px) * k),
2552
+ textcoords="offset points",
2553
+ arrowprops=arrow_kw,
2554
+ zorder=6,
2555
+ annotation_clip=False,
2556
+ )
2557
+ taken.append(final_bb)