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,1318 @@
1
+ """relate() scatter form for mint.explain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from collections.abc import Callable, Sequence
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ from matplotlib.axes import Axes
12
+ from matplotlib.ticker import (
13
+ FuncFormatter,
14
+ MaxNLocator,
15
+ )
16
+ from matplotlib.transforms import Bbox
17
+
18
+ from ..annotations import _relax_positions_pt
19
+ from .core import (
20
+ MAX_COLORED_SERIES,
21
+ ExplainError,
22
+ Panel,
23
+ _clean_sign,
24
+ _Ctx,
25
+ _guarded,
26
+ _issue,
27
+ _jsonable,
28
+ _names,
29
+ _narrow_log_ticks,
30
+ _plain,
31
+ _reference_line,
32
+ _resolve_x_unit,
33
+ _sig_text,
34
+ _slope_ci,
35
+ _small_n_caution,
36
+ _tick_label,
37
+ _values_array,
38
+ )
39
+
40
+ # --------------------------------------------------------------------------- #
41
+ # relate
42
+ # --------------------------------------------------------------------------- #
43
+
44
+
45
+ _SUPER_DIGITS = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079" # ⁰¹²³⁴⁵⁶⁷⁸⁹
46
+
47
+
48
+ def _reciprocal_unit(unit: str) -> str | None:
49
+ """The unit a reciprocal one inverts, with the positive power: "µm⁻½" -> "µm½",
50
+ "K⁻¹" -> "K", "s^-1" -> "s", "1/s" -> "s". None unless ``unit`` is one such unit."""
51
+ u = unit.strip()
52
+ m = re.fullmatch(rf"([^\s/·*^]+)\s*\N{{SUPERSCRIPT MINUS}}([{_SUPER_DIGITS}½⅓¼]+)", u)
53
+ if m:
54
+ base, power = m.groups()
55
+ return base if power == "\N{SUPERSCRIPT ONE}" else base + power
56
+ m = re.fullmatch(r"([^\s/·*^]+)\s*\^\s*\(?\s*-\s*([\d./]+)\s*\)?", u)
57
+ if m:
58
+ base, power = m.groups()
59
+ return base if power == "1" else f"{base}^{power}"
60
+ m = re.fullmatch(r"1\s*/\s*([^\s/·*^]+)", u)
61
+ return m.group(1) if m else None
62
+
63
+
64
+ def _line_text(slope: float, intercept: float, x_name: str, y_name: str) -> str:
65
+ """``y = 2.1·x + 3.4`` with Unicode minus and three significant figures."""
66
+ sign = "\N{MINUS SIGN}" if intercept < 0 else "+"
67
+ return f"{y_name} = {_sig_text(slope)}\N{MIDDLE DOT}{x_name} {sign} {_sig_text(abs(intercept))}"
68
+
69
+
70
+ def _strength(r: float) -> str:
71
+ return (
72
+ "no"
73
+ if not math.isfinite(r) or abs(r) < 0.2
74
+ else "weak"
75
+ if abs(r) < 0.5
76
+ else "moderate"
77
+ if abs(r) < 0.8
78
+ else "strong"
79
+ )
80
+
81
+
82
+ def _r_text(r: float) -> str:
83
+ return _clean_sign(f"{r:.2f}") if math.isfinite(r) else "n/a"
84
+
85
+
86
+ _FRONTIER_MODES: dict[str, tuple[int, int]] = {
87
+ "upper-left": (-1, 1), # lower x, higher y (capability vs cost/latency)
88
+ "upper-right": (1, 1), # higher x, higher y
89
+ "lower-left": (-1, -1), # lower x, lower y
90
+ "lower-right": (1, -1), # higher x, lower y
91
+ }
92
+ _MAX_LABEL_ALL = 24
93
+
94
+
95
+ def _pareto_indices(xs: np.ndarray, ys: np.ndarray, mode: str) -> list[int]:
96
+ """Return indices of non-dominated Pareto frontier points ordered by ascending x."""
97
+ sx, sy = _FRONTIER_MODES[mode]
98
+ # Point j dominates i if sx*x_j >= sx*x_i and sy*y_j >= sy*y_i with at least one strict.
99
+ n = len(xs)
100
+ keep: list[int] = []
101
+ for i in range(n):
102
+ dominated = False
103
+ for j in range(n):
104
+ if i == j:
105
+ continue
106
+ if (
107
+ sx * xs[j] >= sx * xs[i] - 1e-12
108
+ and sy * ys[j] >= sy * ys[i] - 1e-12
109
+ and (sx * xs[j] > sx * xs[i] + 1e-12 or sy * ys[j] > sy * ys[i] + 1e-12)
110
+ ):
111
+ dominated = True
112
+ break
113
+ if not dominated:
114
+ keep.append(i)
115
+ keep.sort(key=lambda idx: (float(xs[idx]), float(ys[idx])))
116
+ return keep
117
+
118
+
119
+ @_guarded("relate")
120
+ def relate(
121
+ x: Sequence[float] | str,
122
+ y: Sequence[float] | str,
123
+ *,
124
+ x_label: str,
125
+ y_label: str,
126
+ data: Any = None,
127
+ title: str | None = None,
128
+ names: Sequence[str] | str | None = None,
129
+ groups: Sequence[str] | str | None = None,
130
+ highlight: str | Sequence[str] | None = None,
131
+ fit: bool = False,
132
+ frontier: bool | str = False,
133
+ label_all: bool = False,
134
+ connect_groups: bool = False,
135
+ log_x: bool = False,
136
+ log_y: bool = False,
137
+ reference: float | tuple[float, str] | None = None,
138
+ unit: str | None = None,
139
+ x_unit: str | None = None,
140
+ callouts: Sequence[tuple[Any, float, str]] | None = None,
141
+ regions: Sequence[tuple[Any, Any, str]] | None = None,
142
+ ) -> Panel:
143
+ """Do two measures move together? A scatter with both axes named.
144
+
145
+ ``names`` labels the points so ``highlight`` can call out up to three of
146
+ them, or set ``label_all=True`` (with ``names=``, up to 24 points) to label
147
+ every point directly with collision avoidance. ``groups`` gives each point
148
+ a group (at most four), coloured and labelled on the plot; ``highlight``
149
+ may then name a group, and ``connect_groups=True`` draws trajectory lines
150
+ connecting points within each group in x order. Pass ``data=`` (rows or
151
+ DataFrame) to read ``x``, ``y``, ``names``, and ``groups`` by column name.
152
+ ``fit=True`` adds a least-squares line (one per group) and reports r, n,
153
+ slope and intercept. ``frontier=True`` (or ``"upper-left"`` |
154
+ ``"upper-right"`` | ``"lower-left"`` | ``"lower-right"``) draws the exact
155
+ non-dominated Pareto frontier envelope and lists frontier items in ``facts``.
156
+ ``reference=(value, "label")`` draws a horizontal line at that y.
157
+ """
158
+ if not x_label or not y_label:
159
+ raise ExplainError(
160
+ "relate() needs x_label and y_label.",
161
+ fix_hint='Name both measures with their units, e.g. x_label="Batch size", '
162
+ 'y_label="Throughput (req/s)".',
163
+ )
164
+ frontier_mode: str | None = None
165
+ if frontier is True:
166
+ frontier_mode = "upper-left"
167
+ elif isinstance(frontier, str):
168
+ key = frontier.strip().lower().replace("_", "-").replace(" ", "-")
169
+ if key not in _FRONTIER_MODES:
170
+ raise ExplainError(
171
+ f"relate(frontier={frontier!r}) is not a valid frontier direction.",
172
+ fix_hint=f"Use True/'upper-left', or one of: {', '.join(_FRONTIER_MODES)}.",
173
+ )
174
+ frontier_mode = key
175
+ elif frontier not in (False, None):
176
+ raise ExplainError(
177
+ f"relate(frontier={frontier!r}) must be a bool or direction string.",
178
+ fix_hint="Use frontier=True (upper-left: high y, low x) or 'upper-right'/'lower-left'/'lower-right'.",
179
+ )
180
+ if data is not None:
181
+ from .._tabular import resolve_relate_table
182
+
183
+ x, y, names, groups = resolve_relate_table(
184
+ data,
185
+ x_col=x,
186
+ y_col=y,
187
+ names=names,
188
+ groups=groups,
189
+ )
190
+ xs = _values_array(x, "relate(x)")
191
+ ys = _values_array(y, "relate(y)")
192
+ if xs.shape != ys.shape or xs.ndim != 1:
193
+ raise ExplainError(
194
+ f"relate() got {xs.size} x values and {ys.size} y values.",
195
+ fix_hint="Pass two equal-length lists of numbers.",
196
+ )
197
+ keep = np.isfinite(xs) & np.isfinite(ys)
198
+ n_dropped = int((~keep).sum())
199
+ point_names = [str(nm) for nm in names] if names is not None else None
200
+ if point_names is not None and len(point_names) != xs.size:
201
+ raise ExplainError(
202
+ "relate(names) must have one name per point.",
203
+ fix_hint="Pass names aligned with x and y, or omit names.",
204
+ )
205
+ point_groups = [str(g) for g in groups] if groups is not None else None
206
+ if point_groups is not None and len(point_groups) != xs.size:
207
+ raise ExplainError(
208
+ "relate(groups) must have one group label per point.",
209
+ fix_hint='Pass groups aligned with x and y, e.g. groups=["A", "A", "B", ...].',
210
+ )
211
+ group_names = list(dict.fromkeys(point_groups)) if point_groups is not None else []
212
+ if len(group_names) > MAX_COLORED_SERIES:
213
+ raise ExplainError(
214
+ f"relate(groups) has {len(group_names)} groups; more than {MAX_COLORED_SERIES} "
215
+ "colours cannot be told apart or held in mind.",
216
+ fix_hint=f"relate(groups=) takes at most {MAX_COLORED_SERIES} groups: merge groups, "
217
+ "drop groups= and highlight= the 1-3 points the takeaway names, or use one relate() "
218
+ "panel per set of groups.",
219
+ rule="too_many_series",
220
+ )
221
+ hl_groups: list[str] = []
222
+ hl: list[str] = []
223
+ if highlight is not None:
224
+ wanted = [highlight] if isinstance(highlight, str) else [str(h) for h in highlight]
225
+ if group_names and all(h in group_names for h in wanted):
226
+ hl_groups = _names(wanted, group_names, "relate(highlight)")
227
+ elif point_names is None:
228
+ raise ExplainError(
229
+ "relate(highlight) needs names= (or groups=) to know which points to call out.",
230
+ fix_hint="Pass names=[...] aligned with x and y, or name a group from groups=.",
231
+ )
232
+ else:
233
+ hl = _names(wanted, point_names, "relate(highlight)")
234
+ ref = _reference_line(reference, "relate(reference)")
235
+ spec_points = {
236
+ "x": _jsonable(xs),
237
+ "y": _jsonable(ys),
238
+ "names": point_names,
239
+ "groups": point_groups,
240
+ }
241
+ xs, ys = xs[keep], ys[keep]
242
+ if point_names is not None:
243
+ point_names = [nm for nm, ok in zip(point_names, keep, strict=True) if ok]
244
+ if point_groups is not None:
245
+ point_groups = [g for g, ok in zip(point_groups, keep, strict=True) if ok]
246
+ if label_all:
247
+ if point_names is None:
248
+ raise ExplainError(
249
+ "relate(label_all=True) needs names= to know what to label each point.",
250
+ fix_hint="Pass names=[...] aligned with x and y (or column name with data=).",
251
+ )
252
+ if xs.size > _MAX_LABEL_ALL:
253
+ raise ExplainError(
254
+ f"relate(label_all=True) got {xs.size} points; labelling more than {_MAX_LABEL_ALL} "
255
+ "points creates unreadable clutter.",
256
+ fix_hint=f"Keep at most {_MAX_LABEL_ALL} points with label_all=True, or drop label_all and use highlight= for 1-3 focal points.",
257
+ rule="too_many_items",
258
+ )
259
+ if connect_groups and not group_names:
260
+ raise ExplainError(
261
+ "relate(connect_groups=True) needs groups= to know which points form each trajectory.",
262
+ fix_hint='Pass groups=[...] (or column name with data=), e.g. groups="family".',
263
+ )
264
+ if xs.size < 3:
265
+ raise ExplainError(
266
+ f"relate() has {xs.size} complete points; a relationship needs >= 3.",
267
+ fix_hint="Use compare() for a couple of items.",
268
+ )
269
+ if (log_x and xs.min() <= 0) or (log_y and ys.min() <= 0):
270
+ raise ExplainError(
271
+ "relate() log axes need strictly positive values.",
272
+ fix_hint="Drop log_x/log_y or remove non-positive points.",
273
+ )
274
+ if log_y and ref is not None and ref[0] <= 0:
275
+ raise ExplainError(
276
+ "relate(reference) must be positive on a log y axis.",
277
+ fix_hint="Drop the reference or log_y=True.",
278
+ )
279
+ region_items, regions_spec = _parse_relate_regions(regions, log_x=log_x)
280
+ callout_items, callouts_spec = _parse_relate_callouts(callouts, log_x=log_x, log_y=log_y)
281
+ fx = np.log10(xs) if log_x else xs
282
+ fy = np.log10(ys) if log_y else ys
283
+
284
+ def _fit(mask: np.ndarray) -> tuple[float, float, float]:
285
+ gx, gy = fx[mask], fy[mask]
286
+ if gx.size < 2:
287
+ return float("nan"), float("nan"), float("nan")
288
+ r_val = (
289
+ float(np.corrcoef(gx, gy)[0, 1]) if np.ptp(gx) > 0 and np.ptp(gy) > 0 else float("nan")
290
+ )
291
+ if np.ptp(gx) > 0:
292
+ m, b = np.polyfit(gx, gy, 1)
293
+ return r_val, float(m), float(b)
294
+ return r_val, float("nan"), float("nan")
295
+
296
+ if unit is not None and not isinstance(unit, str):
297
+ raise ExplainError(
298
+ f"relate(unit={unit!r}) must be a string.",
299
+ fix_hint='Pass the y unit as text, e.g. unit="MPa".',
300
+ )
301
+ y_unit = (unit or "").strip() or None
302
+ x_unit_given = x_unit
303
+ x_unit = _resolve_x_unit(x_unit, x_label, "relate")
304
+ everyone = np.ones(xs.size, bool)
305
+ r, slope, intercept = _fit(everyone)
306
+ strength = _strength(r)
307
+ direction = "" if strength == "no" else (" positive" if r > 0 else " negative")
308
+ space = " in log space" if (log_x or log_y) else ""
309
+ x_sym = "log\N{SUBSCRIPT ONE}\N{SUBSCRIPT ZERO}(x)" if log_x else "x"
310
+ y_sym = "log\N{SUBSCRIPT ONE}\N{SUBSCRIPT ZERO}(y)" if log_y else "y"
311
+ group_masks = {
312
+ g: np.array([pg == g for pg in point_groups], dtype=bool) # type: ignore[union-attr]
313
+ for g in group_names
314
+ }
315
+ group_fits = {g: _fit(mask) for g, mask in group_masks.items()}
316
+
317
+ def _slope_fact(shown: str, mask: np.ndarray, m: float, b: float) -> str | None:
318
+ """A fitted slope with its 95% CI, e.g. "Cu-Zn: slope 327 (95% CI 270–385) MPa per µm".
319
+
320
+ A log-space slope is stated per log₁₀ unit, without the axis units.
321
+ """
322
+ lo, hi = _slope_ci(fx[mask], fy[mask], m, b)
323
+ if not (math.isfinite(lo) and math.isfinite(hi)):
324
+ return None
325
+ inverse = _reciprocal_unit(x_unit) if x_unit else None
326
+ if space:
327
+ per = f"{y_sym} per {x_sym}"
328
+ elif inverse:
329
+ # Per a reciprocal unit is times the unit: "MPa·µm½", not "MPa per µm⁻½".
330
+ per = f"{y_unit}\N{MIDDLE DOT}{inverse}" if y_unit else inverse
331
+ else:
332
+ y_part = f"{y_unit} " if y_unit else ""
333
+ per = f"{y_part}per {x_unit}" if x_unit else f"{y_part}per unit x"
334
+ return (
335
+ f"{shown}: slope{space} {_sig_text(m)} (95% CI {_sig_text(lo)}\N{EN DASH}"
336
+ f"{_sig_text(hi)}) {per}"
337
+ )
338
+
339
+ pooled = (
340
+ f"Pearson r = {_r_text(r)} (n = {xs.size}): {strength}{direction} linear relationship"
341
+ + space
342
+ )
343
+ facts: list[str] = [] if group_names else [pooled]
344
+ if fit and not group_names and math.isfinite(slope):
345
+ facts.append(
346
+ f"fitted line{space}: {_line_text(slope, intercept, x_sym, y_sym)}"
347
+ + (f" (x = {x_label}, y = {y_label})" if not space else "")
348
+ )
349
+ ci = _slope_fact("fitted line", everyone, slope, intercept)
350
+ if ci:
351
+ facts.append(ci)
352
+ for g in group_names:
353
+ g_r, g_m, g_b = group_fits[g]
354
+ text = f"{g}: r = {_r_text(g_r)}, n = {int(group_masks[g].sum())}"
355
+ if fit and math.isfinite(g_m):
356
+ text += f"; fitted line{space}: {_line_text(g_m, g_b, x_sym, y_sym)}"
357
+ facts.append(text)
358
+ if fit:
359
+ for g in group_names:
360
+ _g_r, g_m, g_b = group_fits[g]
361
+ ci = _slope_fact(g, group_masks[g], g_m, g_b) if math.isfinite(g_m) else None
362
+ if ci:
363
+ facts.append(ci)
364
+ # Alt text: every group's r (and line), then the pooled r; else the pooled r.
365
+ alt_facts = facts[: len(group_names)] if group_names else facts[:1]
366
+ if group_names:
367
+ # Pooled r mixes the groups (Simpson's paradox): stated after the per-group r.
368
+ facts.append(
369
+ f"pooled across groups: r = {_r_text(r)}, n = {xs.size}{space} "
370
+ "(mixes groups; see per-group r)"
371
+ )
372
+ alt_facts.append(facts[-1])
373
+ caution = _small_n_caution(
374
+ {g: int(group_masks[g].sum()) for g in group_names},
375
+ "r is a rough estimate" + (" and so is the fitted line" if fit else ""),
376
+ )
377
+ if caution:
378
+ facts.append(caution)
379
+ frontier_idx: list[int] = (
380
+ _pareto_indices(fx, fy, frontier_mode) if frontier_mode is not None else []
381
+ )
382
+ if frontier_mode is not None and frontier_idx:
383
+ if point_names is not None:
384
+ f_names = ", ".join(point_names[i] for i in frontier_idx)
385
+ facts.append(
386
+ f"Pareto frontier ({frontier_mode}, {len(frontier_idx)} of {xs.size}): {f_names}"
387
+ )
388
+ else:
389
+ facts.append(f"Pareto frontier ({frontier_mode}): {len(frontier_idx)} of {xs.size} points")
390
+ if n_dropped:
391
+ facts.append(
392
+ f"{n_dropped} point{'s' if n_dropped > 1 else ''} with a missing value dropped"
393
+ )
394
+ issues: list[dict[str, Any]] = []
395
+ if fit and group_names:
396
+ # One line per group: judge each drawn fit, and warn only when none is strong
397
+ # enough to carry a line (a flat fit next to a steep one is often the finding).
398
+ drawn = {g: group_fits[g][0] for g in group_names if math.isfinite(group_fits[g][1])}
399
+ if drawn and all(_strength(g_r) in {"no", "weak"} for g_r in drawn.values()):
400
+ listed = ", ".join(f"{g} r = {_r_text(g_r)}" for g, g_r in drawn.items())
401
+ issues.append(
402
+ _issue(
403
+ "fit_on_weak_relationship",
404
+ "warning",
405
+ f"fit=True draws a line through a weak relationship in every group ({listed}).",
406
+ "Drop fit=True, or say in the title that the relationship is weak.",
407
+ )
408
+ )
409
+ elif fit and strength in {"no", "weak"}:
410
+ issues.append(
411
+ _issue(
412
+ "fit_on_weak_relationship",
413
+ "warning",
414
+ f"fit=True draws a line through a {strength} relationship (r = {_r_text(r)}).",
415
+ "Drop fit=True, or say in the title that the relationship is weak.",
416
+ )
417
+ )
418
+
419
+ def _draw(ctx: _Ctx, ax: Axes) -> Callable[[], None] | None:
420
+ sz = ctx.sizes
421
+ theme = ctx.theme
422
+ effects = ctx.line_effects()
423
+ if theme.hide_spines:
424
+ for spine in ax.spines.values():
425
+ spine.set_visible(False)
426
+ if theme.grid_style != "none" and theme.grid_lw > 0:
427
+ ax.grid(
428
+ axis="both",
429
+ color=theme.grid,
430
+ linestyle=theme.grid_style,
431
+ linewidth=theme.grid_lw,
432
+ )
433
+ else:
434
+ for name in ("top", "right"):
435
+ ax.spines[name].set_visible(False)
436
+ if theme.inline_y_ticks:
437
+ ax.spines["left"].set_visible(False)
438
+ ax.spines["bottom"].set_color(theme.axis)
439
+ ax.spines["bottom"].set_linewidth(theme.axis_lw)
440
+ ax.grid(
441
+ axis="y",
442
+ color=theme.grid,
443
+ linestyle=theme.grid_style,
444
+ linewidth=theme.grid_lw,
445
+ )
446
+ else:
447
+ for name in ("left", "bottom"):
448
+ ax.spines[name].set_color(theme.axis)
449
+ ax.spines[name].set_linewidth(theme.axis_lw)
450
+ ax.grid(False)
451
+ ax.set_axisbelow(True)
452
+ if log_x:
453
+ ax.set_xscale("log")
454
+ if log_y:
455
+ ax.set_yscale("log")
456
+ ax.tick_params(
457
+ length=theme.tick_length,
458
+ width=theme.tick_width,
459
+ color=theme.axis,
460
+ labelsize=sz.small,
461
+ labelcolor=theme.muted,
462
+ )
463
+ if theme.inline_y_ticks:
464
+ ax.tick_params(axis="y", length=0)
465
+ minus = theme.minus_sign
466
+ for axis, is_log in ((ax.xaxis, log_x), (ax.yaxis, log_y)):
467
+ if not is_log:
468
+ axis.set_major_locator(MaxNLocator(nbins=5, steps=[1, 2, 2.5, 5, 10]))
469
+ axis.set_major_formatter(
470
+ FuncFormatter(lambda v, _p, m=minus, a=axis: _tick_label(v, m, a))
471
+ )
472
+ ax.set_xlabel(_plain(x_label, theme), fontsize=sz.small, color=theme.muted, labelpad=3)
473
+ alpha = 0.9 if xs.size <= 40 else (0.6 if xs.size <= 250 else 0.32)
474
+ # Points called out: highlighted names, or (without highlight) names coloured
475
+ # elsewhere in the figure, so a point keeps its entity's colour.
476
+ called = list(hl)
477
+ if not hl and not group_names and point_names:
478
+ called = [nm for nm in dict.fromkeys(point_names) if nm in ctx.colors]
479
+ is_focus = (
480
+ np.array([(nm in called) for nm in point_names])
481
+ if point_names
482
+ else np.zeros(xs.size, bool)
483
+ )
484
+ group_color: dict[str, str] = {}
485
+ if group_names:
486
+ if hl_groups:
487
+ for i, g in enumerate(hl_groups):
488
+ group_color[g] = ctx.colors.get(g, theme.accent_colors[i])
489
+ for g in group_names:
490
+ group_color.setdefault(g, theme.axis)
491
+ else:
492
+ for i, g in enumerate(group_names):
493
+ group_color[g] = ctx.colors.get(g, theme.series_colors[i])
494
+ order = [g for g in group_names if g not in hl_groups] + hl_groups
495
+ for g in order:
496
+ mask = group_masks[g] & ~is_focus
497
+ focus_group = not hl_groups or g in hl_groups
498
+ if connect_groups and int(group_masks[g].sum()) >= 2:
499
+ g_idx = np.flatnonzero(group_masks[g])
500
+ g_idx = g_idx[np.argsort(fx[g_idx], kind="stable")]
501
+ traj_kw: dict[str, Any] = {
502
+ "color": group_color[g],
503
+ "linewidth": (1.25 if focus_group else 0.85) * sz.scale,
504
+ "alpha": 0.7 if focus_group else 0.4,
505
+ "zorder": 2,
506
+ "label": "_trajectory",
507
+ }
508
+ if effects is not None:
509
+ traj_kw["path_effects"] = effects
510
+ ax.plot(xs[g_idx], ys[g_idx], **traj_kw)
511
+ ax.scatter(
512
+ xs[mask],
513
+ ys[mask],
514
+ s=(4.0 * sz.scale) ** 2,
515
+ color=group_color[g],
516
+ alpha=alpha if focus_group else min(alpha, 0.6),
517
+ edgecolor=theme.background,
518
+ linewidth=0.4,
519
+ zorder=3 if focus_group else 2,
520
+ )
521
+ else:
522
+ base_color = theme.axis if called else ctx.default_color
523
+ ax.scatter(
524
+ xs[~is_focus],
525
+ ys[~is_focus],
526
+ s=(4.0 * sz.scale) ** 2,
527
+ color=base_color,
528
+ alpha=alpha,
529
+ edgecolor=theme.background,
530
+ linewidth=0.4,
531
+ zorder=2,
532
+ )
533
+ # Plot highlighted point markers before autoscale_view() so log-axis limits
534
+ # never clip an extreme highlighted point off the canvas.
535
+ called_points: list[tuple[str, int, str]] = []
536
+ for i, name in enumerate(called):
537
+ idx = point_names.index(name) # type: ignore[union-attr]
538
+ col = ctx.colors.get(name, theme.accent_colors[i % len(theme.accent_colors)])
539
+ ax.scatter(
540
+ [xs[idx]],
541
+ [ys[idx]],
542
+ s=(5.4 * sz.scale) ** 2,
543
+ color=col,
544
+ edgecolor=theme.background,
545
+ linewidth=0.7,
546
+ zorder=5,
547
+ )
548
+ called_points.append((name, idx, col))
549
+ if ref is not None:
550
+ ax.axhline(ref[0], color=theme.ink, linewidth=0.7, linestyle=(0, (3, 2)), zorder=2)
551
+ if ref[1]:
552
+ ax.annotate(
553
+ _plain(ref[1], theme),
554
+ (0.0, ref[0]),
555
+ xycoords=("axes fraction", "data"),
556
+ xytext=(2.0, 2.5),
557
+ textcoords="offset points",
558
+ ha="left",
559
+ va="bottom",
560
+ fontsize=sz.small,
561
+ color=theme.muted,
562
+ bbox=ctx.halo_bbox(0.1),
563
+ )
564
+ if label_all:
565
+ ax.margins(x=0.10, y=0.14)
566
+ ax.autoscale_view()
567
+ for axis, is_log in ((ax.xaxis, log_x), (ax.yaxis, log_y)):
568
+ if is_log:
569
+ lo_v, hi_v = sorted(axis.get_view_interval())
570
+ data_hi = float((xs if axis is ax.xaxis else ys).max())
571
+ if axis is ax.yaxis and ref is not None:
572
+ data_hi = max(data_hi, ref[0])
573
+ lims = _narrow_log_ticks(axis, lo_v, hi_v, minus, extend=False, data_hi=data_hi)
574
+ (ax.set_xlim if axis is ax.xaxis else ax.set_ylim)(*lims)
575
+ if region_items:
576
+ saved_xlim, saved_ylim = ax.get_xlim(), ax.get_ylim()
577
+ for r0, r1, _r_lbl in region_items:
578
+ ax.axvspan(
579
+ r0,
580
+ r1,
581
+ color=theme.context_fill,
582
+ alpha=0.12,
583
+ linewidth=0,
584
+ zorder=0,
585
+ )
586
+ ax.set_xlim(*saved_xlim)
587
+ ax.set_ylim(*saved_ylim)
588
+
589
+ if frontier_mode is not None and len(frontier_idx) >= 2:
590
+ ax.plot(
591
+ xs[frontier_idx],
592
+ ys[frontier_idx],
593
+ color=theme.ink,
594
+ linewidth=1.05 * sz.scale,
595
+ linestyle=(0, (4, 2.5)),
596
+ alpha=0.72,
597
+ zorder=2,
598
+ label="_frontier",
599
+ )
600
+ ax.scatter(
601
+ xs[frontier_idx],
602
+ ys[frontier_idx],
603
+ s=(6.8 * sz.scale) ** 2,
604
+ facecolors="none",
605
+ edgecolors=theme.ink,
606
+ linewidths=0.75 * sz.scale,
607
+ alpha=0.65,
608
+ zorder=4,
609
+ )
610
+
611
+ def _fit_line(mask: np.ndarray, m: float, b: float, color: str, z: int) -> None:
612
+ gx = np.linspace(fx[mask].min(), fx[mask].max(), 50)
613
+ gy = m * gx + b
614
+ fit_kw: dict[str, Any] = {
615
+ "color": color,
616
+ "linewidth": 0.9 * sz.scale,
617
+ "zorder": z,
618
+ "label": "_fit",
619
+ }
620
+ if effects is not None:
621
+ fit_kw["path_effects"] = effects
622
+ ax.plot(10**gx if log_x else gx, 10**gy if log_y else gy, **fit_kw)
623
+
624
+ if fit and not group_names and math.isfinite(slope):
625
+ _fit_line(everyone, slope, intercept, theme.ink, 3)
626
+ ax.annotate(
627
+ _plain(f"r = {_r_text(r)}, n = {xs.size}", theme),
628
+ (0.0 if r < 0 else 1.0, 0.0),
629
+ xycoords="axes fraction",
630
+ xytext=(5.0 if r < 0 else -5.0, 5.0),
631
+ textcoords="offset points",
632
+ ha="left" if r < 0 else "right",
633
+ va="bottom",
634
+ fontsize=sz.small,
635
+ color=theme.muted,
636
+ bbox=ctx.halo_bbox(0.15, alpha=0.9),
637
+ )
638
+ point_notes: list[tuple[Any, bool]] = []
639
+ labeled_indices: set[int] = set()
640
+ for name, idx, col in called_points:
641
+ labeled_indices.add(idx)
642
+ right_half = (fx[idx] - fx.min()) > 0.62 * (np.ptp(fx) or 1.0)
643
+ note = ax.annotate(
644
+ _plain(name, theme),
645
+ (xs[idx], ys[idx]),
646
+ xytext=(-6.0 if right_half else 6.0, 5.0),
647
+ textcoords="offset points",
648
+ ha="right" if right_half else "left",
649
+ va="bottom",
650
+ fontsize=sz.small,
651
+ fontweight="bold",
652
+ color=ctx.text_color(col),
653
+ zorder=6,
654
+ bbox=ctx.halo_bbox(0.12),
655
+ )
656
+ point_notes.append((note, right_half))
657
+ if label_all and point_names is not None:
658
+ # Label frontier points first so they claim the cleanest spots, then remaining points.
659
+ ordered_idx = [i for i in frontier_idx if i not in labeled_indices] + [
660
+ i for i in range(xs.size) if i not in labeled_indices and i not in frontier_idx
661
+ ]
662
+ for idx in ordered_idx:
663
+ nm = point_names[idx]
664
+ right_half = (fx[idx] - fx.min()) > 0.62 * (np.ptp(fx) or 1.0)
665
+ if point_groups is not None:
666
+ g = point_groups[idx]
667
+ focus_g = not hl_groups or g in hl_groups
668
+ tcol = ctx.text_color(group_color[g]) if focus_g else theme.muted
669
+ else:
670
+ tcol = theme.ink if idx in frontier_idx else theme.muted
671
+ note = ax.annotate(
672
+ _plain(nm, theme),
673
+ (xs[idx], ys[idx]),
674
+ xytext=(-6.0 if right_half else 6.0, 4.5),
675
+ textcoords="offset points",
676
+ ha="right" if right_half else "left",
677
+ va="bottom",
678
+ fontsize=sz.small,
679
+ fontweight="normal",
680
+ color=tcol,
681
+ zorder=5,
682
+ bbox=ctx.halo_bbox(0.10),
683
+ )
684
+ point_notes.append((note, right_half))
685
+
686
+ def _clear_point_notes(extra_boxes: Sequence[Bbox] = ()) -> None:
687
+ if not point_notes:
688
+ return
689
+ renderer = ctx.fig.canvas.get_renderer()
690
+ ax_box = ax.get_window_extent(renderer)
691
+ avoid_paths = [
692
+ ln.get_transform().transform_path(ln.get_path())
693
+ for ln in ax.lines
694
+ if ln.get_visible() and ln.get_label() in {"_fit", "_frontier", "_trajectory"}
695
+ ]
696
+ placed: list[Bbox] = list(extra_boxes)
697
+ for note, right_half in point_notes:
698
+ cands = (
699
+ (
700
+ (-6.0, 5.0, "right", "bottom"),
701
+ (-6.0, -5.0, "right", "top"),
702
+ (-8.0, 0.0, "right", "center"),
703
+ (0.0, 9.0, "center", "bottom"),
704
+ (0.0, -9.0, "center", "top"),
705
+ (6.0, -5.0, "left", "top"),
706
+ (6.0, 5.0, "left", "bottom"),
707
+ (8.0, 0.0, "left", "center"),
708
+ (-8.0, 11.0, "right", "bottom"),
709
+ (-8.0, -11.0, "right", "top"),
710
+ (10.0, -9.0, "left", "top"),
711
+ )
712
+ if right_half
713
+ else (
714
+ (6.0, 5.0, "left", "bottom"),
715
+ (6.0, -5.0, "left", "top"),
716
+ (8.0, 0.0, "left", "center"),
717
+ (0.0, 9.0, "center", "bottom"),
718
+ (0.0, -9.0, "center", "top"),
719
+ (-6.0, 5.0, "right", "bottom"),
720
+ (-6.0, -5.0, "right", "top"),
721
+ (-8.0, 0.0, "right", "center"),
722
+ (8.0, -10.0, "left", "top"),
723
+ (8.0, 11.0, "left", "bottom"),
724
+ (-8.0, 11.0, "right", "bottom"),
725
+ )
726
+ )
727
+ best = cands[0]
728
+ best_score = (999, 999, 999)
729
+ for dx, dy, ha, va in cands:
730
+ note.set_position((dx, dy))
731
+ note.set_ha(ha)
732
+ note.set_va(va)
733
+ bb = note.get_window_extent(renderer)
734
+ outside = int(
735
+ not (
736
+ bb.x0 >= ax_box.x0 - 2
737
+ and bb.x1 <= ax_box.x1 + 2
738
+ and bb.y0 >= ax_box.y0 - 2
739
+ and bb.y1 <= ax_box.y1 + 2
740
+ )
741
+ )
742
+ n_other = sum(1 for pb in placed if bb.overlaps(pb))
743
+ n_line = sum(1 for p in avoid_paths if p.intersects_bbox(bb, filled=False))
744
+ score = (outside, n_other, n_line)
745
+ if score < best_score:
746
+ best_score = score
747
+ best = (dx, dy, ha, va)
748
+ if score == (0, 0, 0):
749
+ break
750
+ note.set_position((best[0], best[1]))
751
+ note.set_ha(best[2])
752
+ note.set_va(best[3])
753
+ placed.append(note.get_window_extent(renderer))
754
+
755
+ def _finish_annotations(extra_boxes: Sequence[Bbox] = ()) -> None:
756
+ if point_notes:
757
+ _clear_point_notes(extra_boxes=extra_boxes)
758
+ if region_items:
759
+ _place_relate_regions(ctx, ax, region_items, xs, ys, log_x=log_x)
760
+ if callout_items:
761
+ _place_relate_callouts(ctx, ax, callout_items, xs, ys)
762
+
763
+ if not group_names:
764
+ return (
765
+ _finish_annotations
766
+ if (point_notes or region_items or callout_items)
767
+ else None
768
+ )
769
+
770
+ # Group names sit at each group's right end (its fit line end when fitted).
771
+ anchors: list[tuple[str, float, float, str, bool]] = []
772
+ for g in group_names:
773
+ mask = group_masks[g]
774
+ _g_r, g_m, g_b = group_fits[g]
775
+ focus_group = not hl_groups or g in hl_groups
776
+ if fit and math.isfinite(g_m):
777
+ _fit_line(mask, g_m, g_b, group_color[g], 4 if focus_group else 3)
778
+ end_x = float(fx[mask].max())
779
+ ax_x = 10**end_x if log_x else end_x
780
+ end_y = g_m * end_x + g_b
781
+ ax_y = 10**end_y if log_y else end_y
782
+ else:
783
+ idx = int(np.flatnonzero(mask)[int(np.argmax(fx[mask]))])
784
+ ax_x, ax_y = float(xs[idx]), float(ys[idx])
785
+ # Context groups keep a direct label in the muted colour, as grey context
786
+ # lines in trend() do, so no cloud on the plot is left unidentified.
787
+ anchors.append((g, ax_x, ax_y, group_color[g], focus_group))
788
+ notes = [
789
+ ax.annotate(
790
+ _plain(g, theme),
791
+ (px, py),
792
+ xytext=(5.0, 0.0),
793
+ textcoords="offset points",
794
+ ha="left",
795
+ va="center",
796
+ fontsize=sz.small,
797
+ fontweight="bold" if focus else "normal",
798
+ color=ctx.text_color(col) if focus else theme.muted,
799
+ zorder=6,
800
+ bbox=ctx.halo_bbox(0.12),
801
+ annotation_clip=False,
802
+ )
803
+ for g, px, py, col, focus in anchors
804
+ ]
805
+
806
+ def _finish() -> None:
807
+ renderer = ctx.fig.canvas.get_renderer()
808
+ box = ax.get_window_extent(renderer)
809
+ k = ctx.pt_per_px
810
+ ys_pt = np.array([ax.transData.transform((a[1], a[2]))[1] * k for a in anchors])
811
+ placed = _relax_positions_pt(
812
+ ys_pt, sz.small * 1.22, box.y0 * k + sz.small * 0.4, box.y1 * k - sz.small * 0.4
813
+ )
814
+ for note, y0, y1 in zip(notes, ys_pt, placed, strict=True):
815
+ note.set_position((5.0, float(y1 - y0)))
816
+ group_boxes = [n.get_window_extent(renderer) for n in notes]
817
+ _finish_annotations(extra_boxes=group_boxes)
818
+
819
+ return _finish
820
+
821
+ return Panel(
822
+ kind="relate",
823
+ alt_facts=alt_facts,
824
+ title=title,
825
+ label=y_label,
826
+ unit=y_unit,
827
+ spec={
828
+ "title": title,
829
+ "unit": unit,
830
+ "x_unit": x_unit_given,
831
+ "x": spec_points["x"],
832
+ "y": spec_points["y"],
833
+ "x_label": x_label,
834
+ "y_label": y_label,
835
+ "names": spec_points["names"],
836
+ "groups": spec_points["groups"],
837
+ "highlight": (hl_groups or hl) or None,
838
+ "fit": fit or None,
839
+ "frontier": frontier_mode,
840
+ "label_all": label_all or None,
841
+ "connect_groups": connect_groups or None,
842
+ "log_x": log_x or None,
843
+ "log_y": log_y or None,
844
+ "reference": list(ref) if ref else None,
845
+ "regions": regions_spec or None,
846
+ "callouts": callouts_spec or None,
847
+ },
848
+ facts=facts,
849
+ describe=f"Scatter plot of {y_label} against {x_label}, {xs.size} points"
850
+ + (f" in {len(group_names)} groups" if group_names else ""),
851
+ issues=issues,
852
+ _height_mm=lambda w, _m, _s, _t: min(62.0, max(40.0, 0.6 * w)),
853
+ _min_height_mm=lambda _w, _m, _s, _t: 34.0,
854
+ stretch=True,
855
+ _draw=_draw,
856
+ color_items=tuple(dict.fromkeys([*group_names, *(point_names or [])])),
857
+ color_focus=tuple(hl_groups or [*group_names, *hl]),
858
+ color_mode="highlight" if (hl_groups or hl) else ("series" if group_names else "uniform"),
859
+ uses_default=not group_names and not hl,
860
+ )
861
+
862
+
863
+ _MAX_RELATE_CALLOUTS = 4
864
+
865
+
866
+ def _parse_relate_regions(
867
+ regions: Sequence[tuple[Any, Any, str]] | None,
868
+ *,
869
+ log_x: bool,
870
+ ) -> tuple[list[tuple[float, float, str]], list[list[Any]]]:
871
+ """Validate ``relate(regions=[(x0, x1, label), ...])``."""
872
+ from collections.abc import Mapping as _Mapping
873
+
874
+ from .core import _to_float
875
+
876
+ if regions is None:
877
+ return [], []
878
+ if isinstance(regions, (str, bytes, _Mapping)) or not isinstance(regions, Sequence):
879
+ raise ExplainError(
880
+ f"relate(regions) must be a list of (x0, x1, label) tuples, got {type(regions).__name__}.",
881
+ fix_hint='e.g. regions=[(10, 40, "target zone")].',
882
+ )
883
+ parsed: list[tuple[float, float, str]] = []
884
+ spec_out: list[list[Any]] = []
885
+ for idx, item in enumerate(regions):
886
+ if isinstance(item, (str, bytes, _Mapping)) or not isinstance(item, Sequence) or len(item) != 3:
887
+ raise ExplainError(
888
+ f"relate(regions[{idx}]) must be an (x0, x1, label) 3-tuple, got {item!r}.",
889
+ fix_hint='Pass (x0, x1, "short label") for each shaded region.',
890
+ )
891
+ raw0, raw1, label = item
892
+ p0 = _to_float(raw0, f"relate(regions[{idx}]) start")
893
+ p1 = _to_float(raw1, f"relate(regions[{idx}]) end")
894
+ if not (math.isfinite(p0) and math.isfinite(p1)):
895
+ raise ExplainError(
896
+ f"relate(regions[{idx}]) bounds ({raw0!r}, {raw1!r}) must be finite numbers.",
897
+ fix_hint="Use finite numeric bounds for x0 and x1.",
898
+ )
899
+ if p0 >= p1:
900
+ raise ExplainError(
901
+ f"relate(regions[{idx}]) start {raw0!r} must be strictly less than end {raw1!r}.",
902
+ fix_hint="Order each region tuple as (x0, x1, label) with x0 < x1.",
903
+ )
904
+ if log_x and p0 <= 0:
905
+ raise ExplainError(
906
+ f"relate(regions[{idx}]) requires positive x bounds on a log_x axis.",
907
+ fix_hint="Use positive x0 and x1 values when log_x=True.",
908
+ )
909
+ text = str(label).strip()
910
+ parsed.append((p0, p1, text))
911
+ spec_out.append([float(p0), float(p1), text])
912
+ return parsed, spec_out
913
+
914
+
915
+ def _parse_relate_callouts(
916
+ callouts: Sequence[tuple[Any, float, str]] | None,
917
+ *,
918
+ log_x: bool,
919
+ log_y: bool,
920
+ ) -> tuple[list[tuple[float, float, str]], list[list[Any]]]:
921
+ """Validate ``relate(callouts=[(x, y, note), ...])`` (max 4)."""
922
+ from collections.abc import Mapping as _Mapping
923
+
924
+ from .core import _to_float
925
+
926
+ if callouts is None:
927
+ return [], []
928
+ if isinstance(callouts, (str, bytes, _Mapping)) or not isinstance(callouts, Sequence):
929
+ raise ExplainError(
930
+ f"relate(callouts) must be a list of (x, y, note) tuples, got {type(callouts).__name__}.",
931
+ fix_hint='e.g. callouts=[(12.0, 94.5, "Pareto knee")].',
932
+ )
933
+ if len(callouts) > _MAX_RELATE_CALLOUTS:
934
+ raise ExplainError(
935
+ f"relate(callouts) got {len(callouts)} callouts; at most {_MAX_RELATE_CALLOUTS} stay legible.",
936
+ fix_hint=f"Keep at most {_MAX_RELATE_CALLOUTS} callouts highlighting key points.",
937
+ )
938
+ parsed: list[tuple[float, float, str]] = []
939
+ spec_out: list[list[Any]] = []
940
+ for idx, item in enumerate(callouts):
941
+ if isinstance(item, (str, bytes, _Mapping)) or not isinstance(item, Sequence) or len(item) != 3:
942
+ raise ExplainError(
943
+ f"relate(callouts[{idx}]) must be an (x, y, note) 3-tuple, got {item!r}.",
944
+ fix_hint='Pass (x, y, "short note") for each callout.',
945
+ )
946
+ raw_x, raw_y, note = item
947
+ px = _to_float(raw_x, f"relate(callouts[{idx}]) x")
948
+ py = _to_float(raw_y, f"relate(callouts[{idx}]) y")
949
+ if not (math.isfinite(px) and math.isfinite(py)):
950
+ raise ExplainError(
951
+ f"relate(callouts[{idx}]) coordinates ({raw_x!r}, {raw_y!r}) must be finite numbers.",
952
+ fix_hint="Pass finite numeric (x, y) coordinates.",
953
+ )
954
+ if log_x and px <= 0:
955
+ raise ExplainError(
956
+ f"relate(callouts[{idx}]) x must be positive on a log_x axis.",
957
+ fix_hint="Use positive x values when log_x=True.",
958
+ )
959
+ if log_y and py <= 0:
960
+ raise ExplainError(
961
+ f"relate(callouts[{idx}]) y must be positive on a log_y axis.",
962
+ fix_hint="Use positive y values when log_y=True.",
963
+ )
964
+ text = str(note).strip()
965
+ if not text:
966
+ raise ExplainError(
967
+ f"relate(callouts[{idx}]) has an empty note.",
968
+ fix_hint='Pass a short descriptive note, e.g. (12.0, 94.5, "best trade-off").',
969
+ )
970
+ parsed.append((px, py, text))
971
+ spec_out.append([float(px), float(py), text])
972
+ return parsed, spec_out
973
+
974
+
975
+ def _relate_text_boxes(ctx: _Ctx, exclude: Any = None) -> list[Bbox]:
976
+ from matplotlib.text import Text
977
+
978
+ renderer = ctx.fig.canvas.get_renderer()
979
+ return [
980
+ t.get_window_extent(renderer)
981
+ for t in ctx.fig.findobj(Text)
982
+ if t is not exclude and t.get_visible() and t.get_text().strip() and t.get_alpha() != 0
983
+ ]
984
+
985
+
986
+ def _relate_line_paths(ax: Axes) -> list[Any]:
987
+ grid = {id(g) for g in (*ax.get_xgridlines(), *ax.get_ygridlines())}
988
+ return [
989
+ ln.get_transform().transform_path(ln.get_path())
990
+ for ln in ax.lines
991
+ if id(ln) not in grid
992
+ and ln.get_visible()
993
+ and len(ln.get_xdata()) >= 2
994
+ and ln.get_linestyle() not in ("None", "", " ")
995
+ and ln.get_linewidth() > 0
996
+ ]
997
+
998
+
999
+ def _relate_pad_bbox(bb: Bbox, pad: float = 1.5) -> Bbox:
1000
+ return Bbox.from_extents(bb.x0 - pad, bb.y0 - pad, bb.x1 + pad, bb.y1 + pad)
1001
+
1002
+
1003
+ def _place_relate_regions(
1004
+ ctx: _Ctx,
1005
+ ax: Axes,
1006
+ regions: Sequence[tuple[float, float, str]],
1007
+ xs: np.ndarray,
1008
+ ys: np.ndarray,
1009
+ *,
1010
+ log_x: bool = False,
1011
+ ) -> None:
1012
+ """Place muted top labels centered inside shaded regions on relate(), avoiding lines, text & dots."""
1013
+ sz = ctx.sizes
1014
+ theme = ctx.theme
1015
+ renderer = ctx.fig.canvas.get_renderer()
1016
+ frame = ax.get_window_extent(renderer)
1017
+ fig_box = ctx.fig.bbox
1018
+ paths = _relate_line_paths(ax)
1019
+ taken = _relate_text_boxes(ctx)
1020
+ pts_disp = ax.transData.transform(np.column_stack([xs, ys]))
1021
+ x_lo, x_hi = sorted(ax.get_xlim())
1022
+ for r0, r1, text in regions:
1023
+ if not text:
1024
+ continue
1025
+ vis0 = max(r0, x_lo)
1026
+ vis1 = min(r1, x_hi)
1027
+ if vis0 >= vis1:
1028
+ vis0, vis1 = r0, r1
1029
+ mid_x = math.sqrt(vis0 * vis1) if (log_x and vis0 > 0 and vis1 > 0) else 0.5 * (vis0 + vis1)
1030
+ note = ax.annotate(
1031
+ _plain(text, theme),
1032
+ (mid_x, 1.0),
1033
+ xycoords=("data", "axes fraction"),
1034
+ xytext=(0.0, -3.0),
1035
+ textcoords="offset points",
1036
+ ha="center",
1037
+ va="top",
1038
+ fontsize=sz.small,
1039
+ color=theme.muted,
1040
+ zorder=6,
1041
+ bbox=ctx.halo_bbox(0.08, alpha=0.82),
1042
+ annotation_clip=False,
1043
+ )
1044
+ cands = [
1045
+ (mid_x, 1.0, "center", "top", 0.0, -3.0, True),
1046
+ (mid_x, 0.88, "center", "top", 0.0, 0.0, True),
1047
+ (mid_x, 0.0, "center", "bottom", 0.0, 3.0, True),
1048
+ (vis0, 1.0, "left", "top", 3.0, -3.0, True),
1049
+ (vis1, 1.0, "right", "top", -3.0, -3.0, True),
1050
+ (vis0, 0.0, "left", "bottom", 3.0, 3.0, True),
1051
+ (vis1, 0.0, "right", "bottom", -3.0, 3.0, True),
1052
+ (mid_x, 0.72, "center", "top", 0.0, 0.0, True),
1053
+ (mid_x, 0.50, "center", "center", 0.0, 0.0, True),
1054
+ (mid_x, 0.25, "center", "bottom", 0.0, 0.0, True),
1055
+ (mid_x, 1.0, "center", "bottom", 0.0, 2.5, False),
1056
+ ]
1057
+ best = cands[0]
1058
+ best_score = (999, 999, 999, 999, 999)
1059
+ for cx, yfrac, ha, va, dx, dy, inside_pref in cands:
1060
+ note.xy = (cx, yfrac)
1061
+ note.set_ha(ha)
1062
+ note.set_va(va)
1063
+ note.set_position((dx, dy))
1064
+ bb = note.get_window_extent(renderer)
1065
+ pbb = _relate_pad_bbox(bb, 1.5)
1066
+ out_fig = int(
1067
+ not (
1068
+ bb.x0 >= fig_box.x0 + 2
1069
+ and bb.x1 <= fig_box.x1 - 2
1070
+ and bb.y0 >= fig_box.y0 + 2
1071
+ and bb.y1 <= fig_box.y1 - 2
1072
+ )
1073
+ )
1074
+ out_frame = int(
1075
+ not (
1076
+ bb.x0 >= frame.x0 - 2
1077
+ and bb.x1 <= frame.x1 + 2
1078
+ and bb.y0 >= frame.y0 - 2
1079
+ and bb.y1 <= frame.y1 + 2
1080
+ )
1081
+ )
1082
+ n_line = sum(1 for p in paths if p.intersects_bbox(bb, filled=False))
1083
+ n_text = sum(1 for tb in taken if pbb.overlaps(tb))
1084
+ n_dots = int(
1085
+ np.sum(
1086
+ (pts_disp[:, 0] >= bb.x0 - 3)
1087
+ & (pts_disp[:, 0] <= bb.x1 + 3)
1088
+ & (pts_disp[:, 1] >= bb.y0 - 3)
1089
+ & (pts_disp[:, 1] <= bb.y1 + 3)
1090
+ )
1091
+ )
1092
+ score = (out_fig, n_line, n_text, out_frame if inside_pref else out_frame + 1, n_dots)
1093
+ if score < best_score:
1094
+ best_score = score
1095
+ best = (cx, yfrac, ha, va, dx, dy, inside_pref)
1096
+ if score == (0, 0, 0, 0, 0):
1097
+ break
1098
+ note.xy = (best[0], best[1])
1099
+ note.set_ha(best[2])
1100
+ note.set_va(best[3])
1101
+ note.set_position((best[4], best[5]))
1102
+ taken.append(note.get_window_extent(renderer))
1103
+
1104
+
1105
+ def _relate_arrow_segment(
1106
+ ax_px: float, ay_px: float, bb: Bbox
1107
+ ) -> tuple[float, float, Any | None]:
1108
+ """Return ``(start_x_px, start_y_px, trimmed_path)`` from nearest edge of ``bb`` to anchor."""
1109
+ from matplotlib.path import Path as MplPath
1110
+
1111
+ px = min(max(ax_px, bb.x0), bb.x1)
1112
+ py = min(max(ay_px, bb.y0), bb.y1)
1113
+ vx, vy = ax_px - px, ay_px - py
1114
+ seg_len = math.hypot(vx, vy)
1115
+ if seg_len < 7.0:
1116
+ return px, py, None
1117
+ t0 = min(0.35, 3.0 / seg_len)
1118
+ t1 = max(t0 + 0.05, 1.0 - 7.5 / seg_len)
1119
+ s0 = (px + t0 * vx, py + t0 * vy)
1120
+ s1 = (px + t1 * vx, py + t1 * vy)
1121
+ return px, py, MplPath([s0, s1])
1122
+
1123
+
1124
+ def _relate_two_line_wrap(text: str) -> str | None:
1125
+ words = text.split()
1126
+ if len(words) < 2 or "\n" in text:
1127
+ return None
1128
+ best_i = min(
1129
+ range(1, len(words)),
1130
+ key=lambda i: abs(len(" ".join(words[:i])) - len(" ".join(words[i:]))),
1131
+ )
1132
+ return " ".join(words[:best_i]) + "\n" + " ".join(words[best_i:])
1133
+
1134
+
1135
+ def _place_relate_callouts(
1136
+ ctx: _Ctx,
1137
+ ax: Axes,
1138
+ callouts: Sequence[tuple[float, float, str]],
1139
+ xs: np.ndarray,
1140
+ ys: np.ndarray,
1141
+ ) -> None:
1142
+ """Place direct callout annotations with leader arrows on relate(), avoiding lines, text, and arrow crossings."""
1143
+ sz = ctx.sizes
1144
+ theme = ctx.theme
1145
+ renderer = ctx.fig.canvas.get_renderer()
1146
+ frame = ax.get_window_extent(renderer)
1147
+ fig_box = ctx.fig.bbox
1148
+ paths = _relate_line_paths(ax)
1149
+ taken = _relate_text_boxes(ctx)
1150
+ pts_disp = ax.transData.transform(np.column_stack([xs, ys]))
1151
+ k = ctx.pt_per_px
1152
+ arrow_kw = {
1153
+ "arrowstyle": "-|>,head_length=0.35,head_width=0.2",
1154
+ "color": theme.muted,
1155
+ "linewidth": 0.75 * sz.scale,
1156
+ "shrinkA": 2.0,
1157
+ "shrinkB": 3.5,
1158
+ }
1159
+ base_offsets = [
1160
+ (12.0, 14.0, "left", "bottom"),
1161
+ (-12.0, 14.0, "right", "bottom"),
1162
+ (12.0, -14.0, "left", "top"),
1163
+ (-12.0, -14.0, "right", "top"),
1164
+ (0.0, 18.0, "center", "bottom"),
1165
+ (0.0, -18.0, "center", "top"),
1166
+ (18.0, 0.0, "left", "center"),
1167
+ (-18.0, 0.0, "right", "center"),
1168
+ (20.0, 22.0, "left", "bottom"),
1169
+ (-20.0, 22.0, "right", "bottom"),
1170
+ (20.0, -22.0, "left", "top"),
1171
+ (-20.0, -22.0, "right", "top"),
1172
+ (14.0, -22.0, "center", "top"),
1173
+ (-14.0, -22.0, "center", "top"),
1174
+ (14.0, 22.0, "center", "bottom"),
1175
+ (-14.0, 22.0, "center", "bottom"),
1176
+ (0.0, 28.0, "center", "bottom"),
1177
+ (0.0, -28.0, "center", "top"),
1178
+ (28.0, 10.0, "left", "bottom"),
1179
+ (-28.0, 10.0, "right", "bottom"),
1180
+ (28.0, -10.0, "left", "top"),
1181
+ (-28.0, -10.0, "right", "top"),
1182
+ (0.0, 42.0, "center", "bottom"),
1183
+ (0.0, -42.0, "center", "top"),
1184
+ (32.0, 34.0, "left", "bottom"),
1185
+ (-32.0, 34.0, "right", "bottom"),
1186
+ (32.0, -34.0, "left", "top"),
1187
+ (-32.0, -34.0, "right", "top"),
1188
+ (44.0, 0.0, "left", "center"),
1189
+ (-44.0, 0.0, "right", "center"),
1190
+ ]
1191
+ for cx, cy, text in callouts:
1192
+ disp = ax.transData.transform((cx, cy))
1193
+ ax_px, ay_px = float(disp[0]), float(disp[1])
1194
+ fx, fy = ax.transAxes.inverted().transform(disp)
1195
+ note = ax.annotate(
1196
+ _plain(text, theme),
1197
+ xy=(cx, cy),
1198
+ xycoords="data",
1199
+ xytext=(12.0, 14.0),
1200
+ textcoords="offset points",
1201
+ ha="left",
1202
+ va="bottom",
1203
+ fontsize=sz.small,
1204
+ color=theme.ink,
1205
+ zorder=7,
1206
+ bbox=ctx.halo_bbox(0.16, alpha=0.92),
1207
+ annotation_clip=False,
1208
+ )
1209
+ prefer_dx = -1.0 if fx > 0.55 else 1.0
1210
+ prefer_dy = -1.0 if fy > 0.60 else 1.0
1211
+ ordered = sorted(
1212
+ base_offsets,
1213
+ key=lambda c: (
1214
+ int(math.hypot(c[0], c[1]) // 18),
1215
+ 0 if c[0] * prefer_dx >= 0 else 1,
1216
+ 0 if c[1] * prefer_dy >= 0 else 1,
1217
+ math.hypot(c[0], c[1]),
1218
+ ),
1219
+ )
1220
+ text_variants = [text]
1221
+ wrapped = _relate_two_line_wrap(text)
1222
+ if wrapped is not None:
1223
+ text_variants.append(wrapped)
1224
+
1225
+ best_variant = text
1226
+ best = ordered[0]
1227
+ best_score: tuple[int, int, int, int, int, int, int, int, float] = (
1228
+ 999,
1229
+ 999,
1230
+ 999,
1231
+ 999,
1232
+ 999,
1233
+ 999,
1234
+ 999,
1235
+ 999,
1236
+ 1e9,
1237
+ )
1238
+ for v_idx, variant in enumerate(text_variants):
1239
+ note.set_text(_plain(variant, theme))
1240
+ for dx, dy, ha, va in ordered:
1241
+ note.set_position((dx, dy))
1242
+ note.set_ha(ha)
1243
+ note.set_va(va)
1244
+ bb = note.get_window_extent(renderer)
1245
+ pbb = _relate_pad_bbox(bb, 1.5)
1246
+ out_fig = int(
1247
+ not (
1248
+ bb.x0 >= fig_box.x0 + 3
1249
+ and bb.x1 <= fig_box.x1 - 3
1250
+ and bb.y0 >= fig_box.y0 + 3
1251
+ and bb.y1 <= fig_box.y1 - 3
1252
+ )
1253
+ )
1254
+ out_frame = int(
1255
+ not (
1256
+ bb.x0 >= frame.x0 + 1
1257
+ and bb.x1 <= frame.x1 - 1
1258
+ and bb.y0 >= frame.y0 + 3.5
1259
+ and bb.y1 <= frame.y1 - 1
1260
+ )
1261
+ )
1262
+ n_line = sum(1 for p in paths if p.intersects_bbox(bb, filled=False))
1263
+ n_text = sum(1 for tb in taken if pbb.overlaps(tb))
1264
+ _, _, seg_path = _relate_arrow_segment(ax_px, ay_px, bb)
1265
+ if seg_path is not None:
1266
+ n_arrow_text = sum(
1267
+ 1
1268
+ for tb in taken
1269
+ if seg_path.intersects_bbox(_relate_pad_bbox(tb, 1.0), filled=True)
1270
+ )
1271
+ n_arrow_line = sum(1 for p in paths if seg_path.intersects_path(p, filled=False))
1272
+ else:
1273
+ n_arrow_text = 0
1274
+ n_arrow_line = 0
1275
+ n_dots = int(
1276
+ np.sum(
1277
+ (pts_disp[:, 0] >= bb.x0 - 2)
1278
+ & (pts_disp[:, 0] <= bb.x1 + 2)
1279
+ & (pts_disp[:, 1] >= bb.y0 - 2)
1280
+ & (pts_disp[:, 1] <= bb.y1 + 2)
1281
+ )
1282
+ )
1283
+ score = (
1284
+ out_fig,
1285
+ n_line,
1286
+ n_text,
1287
+ n_arrow_text,
1288
+ n_arrow_line,
1289
+ out_frame,
1290
+ n_dots,
1291
+ v_idx,
1292
+ math.hypot(dx, dy),
1293
+ )
1294
+ if score < best_score:
1295
+ best_score = score
1296
+ best = (dx, dy, ha, va)
1297
+ best_variant = variant
1298
+ if score[:7] == (0, 0, 0, 0, 0, 0, 0):
1299
+ break
1300
+ if best_score[:7] == (0, 0, 0, 0, 0, 0, 0):
1301
+ break
1302
+ note.set_text(_plain(best_variant, theme))
1303
+ note.set_position((best[0], best[1]))
1304
+ note.set_ha(best[2])
1305
+ note.set_va(best[3])
1306
+ final_bb = note.get_window_extent(renderer)
1307
+ start_px, start_py, _ = _relate_arrow_segment(ax_px, ay_px, final_bb)
1308
+ ax.annotate(
1309
+ "",
1310
+ xy=(cx, cy),
1311
+ xycoords="data",
1312
+ xytext=((start_px - ax_px) * k, (start_py - ay_px) * k),
1313
+ textcoords="offset points",
1314
+ arrowprops=arrow_kw,
1315
+ zorder=6,
1316
+ annotation_clip=False,
1317
+ )
1318
+ taken.append(final_bb)