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
mintfig/__init__.py ADDED
@@ -0,0 +1,162 @@
1
+ """mintfig — Nature- and Science-ready scientific figure library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .annotations import (
6
+ despine,
7
+ direct_labels,
8
+ emphasize,
9
+ ghost_context,
10
+ range_frame,
11
+ scalebar,
12
+ sig_bracket,
13
+ slopegraph,
14
+ sparkline,
15
+ style_colorbar,
16
+ style_heatmap,
17
+ subtle_grid,
18
+ tufte_boxplot,
19
+ zoom_inset,
20
+ )
21
+ from .audit import audit_figure, audit_layout
22
+ from .brief import Brief, Session, brief
23
+ from .bundle import BundleResult, bundle_figure
24
+ from .edit import edit
25
+ from .epistemic import audit_epistemic, build_narrative
26
+ from .explainer import (
27
+ ExplainError,
28
+ Explanation,
29
+ Panel,
30
+ change,
31
+ compare,
32
+ custom,
33
+ distribution,
34
+ explain,
35
+ explain_from_spec,
36
+ flow,
37
+ histogram,
38
+ lenient,
39
+ load,
40
+ matrix,
41
+ panel_from_spec,
42
+ relate,
43
+ share,
44
+ table,
45
+ timeline,
46
+ trend,
47
+ waterfall,
48
+ )
49
+ from .export import rasterize_heavy, save_figure
50
+ from .inspect_data import auto_panel, inspect_data, load_table_file
51
+ from .interactive import render_html
52
+ from .palettes import (
53
+ BANNED_COLORMAPS,
54
+ EDITORIAL_COLORMAPS,
55
+ PALETTES,
56
+ get_palette,
57
+ register_colormaps,
58
+ simulate_cvd,
59
+ )
60
+ from .plate import Plate, figure
61
+ from .preflight import CheckResult, PreflightReport, preflight_figure, preflight_pdf
62
+ from .proof import render_proof_sheet
63
+ from .runner import RunResult, run_script
64
+ from .skill import VALID_TARGETS, get_agents_snippet, get_skill_markdown, install_skill
65
+ from .specs import JOURNALS, MM_PER_INCH, JournalSpec, get_spec, in_to_mm, mm_to_in
66
+ from .style import apply, rc_params, resolved_font_name, use
67
+ from .terminal import render_terminal, show_in_terminal
68
+ from .themes import EXPLAIN_PALETTES, THEMES, ExplainPalette, Theme, get_explain_palette, get_theme
69
+
70
+ __version__ = "0.2.0"
71
+
72
+ __all__ = [
73
+ "BANNED_COLORMAPS",
74
+ "EDITORIAL_COLORMAPS",
75
+ "EXPLAIN_PALETTES",
76
+ "JOURNALS",
77
+ "MM_PER_INCH",
78
+ "PALETTES",
79
+ "THEMES",
80
+ "VALID_TARGETS",
81
+ "Brief",
82
+ "BundleResult",
83
+ "CheckResult",
84
+ "ExplainError",
85
+ "ExplainPalette",
86
+ "Explanation",
87
+ "JournalSpec",
88
+ "Panel",
89
+ "Plate",
90
+ "PreflightReport",
91
+ "RunResult",
92
+ "Session",
93
+ "Theme",
94
+ "__version__",
95
+ "apply",
96
+ "audit_epistemic",
97
+ "audit_figure",
98
+ "audit_layout",
99
+ "auto_panel",
100
+ "brief",
101
+ "build_narrative",
102
+ "bundle_figure",
103
+ "change",
104
+ "compare",
105
+ "custom",
106
+ "despine",
107
+ "direct_labels",
108
+ "distribution",
109
+ "edit",
110
+ "emphasize",
111
+ "explain",
112
+ "explain_from_spec",
113
+ "figure",
114
+ "flow",
115
+ "get_agents_snippet",
116
+ "get_explain_palette",
117
+ "get_palette",
118
+ "get_skill_markdown",
119
+ "get_spec",
120
+ "get_theme",
121
+ "ghost_context",
122
+ "histogram",
123
+ "in_to_mm",
124
+ "inspect_data",
125
+ "install_skill",
126
+ "lenient",
127
+ "load",
128
+ "load_table_file",
129
+ "matrix",
130
+ "mm_to_in",
131
+ "panel_from_spec",
132
+ "preflight_figure",
133
+ "preflight_pdf",
134
+ "range_frame",
135
+ "rasterize_heavy",
136
+ "rc_params",
137
+ "register_colormaps",
138
+ "relate",
139
+ "render_html",
140
+ "render_proof_sheet",
141
+ "render_terminal",
142
+ "resolved_font_name",
143
+ "run_script",
144
+ "save_figure",
145
+ "scalebar",
146
+ "share",
147
+ "show_in_terminal",
148
+ "sig_bracket",
149
+ "simulate_cvd",
150
+ "slopegraph",
151
+ "sparkline",
152
+ "style_colorbar",
153
+ "style_heatmap",
154
+ "subtle_grid",
155
+ "table",
156
+ "timeline",
157
+ "trend",
158
+ "tufte_boxplot",
159
+ "use",
160
+ "waterfall",
161
+ "zoom_inset",
162
+ ]
@@ -0,0 +1 @@
1
+ """Modular implementation of mintfig.explain forms, formatting, and layout."""
@@ -0,0 +1,392 @@
1
+ """change() slopegraph form for mint.explain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping, Sequence
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ from matplotlib.axes import Axes
10
+ from matplotlib.transforms import Bbox
11
+
12
+ from ..annotations import _relax_positions_pt
13
+ from .core import (
14
+ _MARGIN_MM,
15
+ MAX_CHANGE_ITEMS,
16
+ MAX_COMPARE_ITEMS,
17
+ PT_TO_MM,
18
+ ExplainError,
19
+ Panel,
20
+ _bare_axes,
21
+ _base_spec,
22
+ _Ctx,
23
+ _diff_with_unit,
24
+ _formatter,
25
+ _guarded,
26
+ _is_strict,
27
+ _Measure,
28
+ _named_values,
29
+ _names,
30
+ _plain,
31
+ _record_adjustment,
32
+ _relative_text,
33
+ _signed,
34
+ _Sizes,
35
+ _with_unit,
36
+ )
37
+
38
+ # --------------------------------------------------------------------------- #
39
+ # change (slopegraph)
40
+ # --------------------------------------------------------------------------- #
41
+
42
+
43
+ #: Narrowest slopegraph plot (mm at scale 1) before change() wraps or drops labels.
44
+ _CHANGE_PLOT_MM = 14.0
45
+ #: Width (pt at scale 1) a wrapped item name may take under its value in change().
46
+ _CHANGE_NAME_PT = 70.0
47
+
48
+
49
+ @_guarded("change")
50
+ def change(
51
+ before: Mapping[str, float] | str,
52
+ after: Mapping[str, float] | str,
53
+ *,
54
+ data: Any = None,
55
+ name: str | None = None,
56
+ labels: Sequence[str] = ("Before", "After"),
57
+ title: str | None = None,
58
+ label: str | None = None,
59
+ unit: str | None = None,
60
+ highlight: str | Sequence[str] | None = None,
61
+ fmt: str | None = None,
62
+ ) -> Panel:
63
+ """What moved between two states? A slopegraph: one line per item, steepness is the change.
64
+
65
+ ``before`` and ``after`` map the same item names to values on one scale,
66
+ or name two columns in ``data=`` (with ``name=`` for the item column).
67
+ """
68
+ if data is not None:
69
+ from .._tabular import resolve_change_table
70
+
71
+ if labels == ("Before", "After") and isinstance(before, str) and isinstance(after, str):
72
+ labels = (before, after)
73
+ before, after = resolve_change_table(
74
+ data,
75
+ before_col=before,
76
+ after_col=after,
77
+ name_col=name,
78
+ )
79
+ elif name is not None:
80
+ raise ExplainError(
81
+ "change(name=...) requires data= with row-shaped records or a DataFrame.",
82
+ fix_hint='Pass data=rows, e.g. mint.change("v1", "v2", data=rows, name="item").',
83
+ )
84
+ left = _named_values(before, "change(before)")
85
+ right = _named_values(after, "change(after)")
86
+ if set(left) != set(right):
87
+ missing = sorted(set(left) ^ set(right))
88
+ shared = [nm for nm in left if nm in right]
89
+ if not _is_strict() and shared:
90
+ left = {nm: left[nm] for nm in shared}
91
+ right = {nm: right[nm] for nm in shared}
92
+ _record_adjustment(f"change(): dropped unmatched item(s) {missing[:6]!r}")
93
+ else:
94
+ raise ExplainError(
95
+ f"change() needs the same items before and after; unmatched: {missing[:6]!r}.",
96
+ fix_hint="Drop items that lack one of the two values, and say so in `note`.",
97
+ )
98
+ if isinstance(labels, (str, bytes)) or len(labels) != 2:
99
+ raise ExplainError(
100
+ "change(labels) needs exactly two names.", fix_hint='e.g. ("2024", "2025").'
101
+ )
102
+ labels = (str(labels[0]), str(labels[1]))
103
+ names = sorted(right, key=lambda nm: right[nm], reverse=True)
104
+ if len(names) > MAX_CHANGE_ITEMS:
105
+ if not _is_strict():
106
+ req_hl = (
107
+ [highlight]
108
+ if isinstance(highlight, str)
109
+ else ([str(h) for h in highlight] if highlight is not None else [])
110
+ )
111
+ keep = [nm for nm in req_hl if nm in right]
112
+ for nm in sorted(names, key=lambda k: abs(right[k] - left[k]), reverse=True):
113
+ if len(keep) >= MAX_CHANGE_ITEMS:
114
+ break
115
+ if nm not in keep:
116
+ keep.append(nm)
117
+ keep_set = set(keep)
118
+ left = {nm: left[nm] for nm in names if nm in keep_set}
119
+ right = {nm: right[nm] for nm in names if nm in keep_set}
120
+ _record_adjustment(f"change(): trimmed {len(names)} items to top {len(keep)} movers")
121
+ names = sorted(right, key=lambda nm: right[nm], reverse=True)
122
+ else:
123
+ raise ExplainError(
124
+ f"change() got {len(names)} items; a slopegraph tangles beyond {MAX_CHANGE_ITEMS}.",
125
+ fix_hint=f"change() takes at most {MAX_CHANGE_ITEMS} items: keep the items the "
126
+ f"takeaway is about, or use compare() on the differences (up to {MAX_COMPARE_ITEMS} "
127
+ "items, baseline= for a reference).",
128
+ rule="too_many_items",
129
+ )
130
+ hl = _names(highlight, names)
131
+ fmt_fn = _formatter([*left.values(), *right.values()], fmt, unit=unit)
132
+ deltas = {nm: right[nm] - left[nm] for nm in names}
133
+ delta_fmt = _formatter(list(deltas.values()), fmt, unit=unit)
134
+
135
+ def _delta_text(name: str) -> str:
136
+ return _signed(delta_fmt(deltas[name]))
137
+
138
+ points = unit is not None and unit.strip().startswith("%")
139
+
140
+ def _moved(name: str) -> str:
141
+ """"+768 ms, +59%"; in points for "%" units ("+5 points"); no percent across zero."""
142
+ shown = _diff_with_unit(_delta_text(name), unit)
143
+ rel = None if points else _relative_text(right[name], left[name], None)
144
+ return f"{shown}, {rel}" if rel else shown
145
+
146
+ def _from_to(name: str) -> str:
147
+ # The unit on both values or on neither: "$0.479 → $0.377", "945 ms → 1,379 ms".
148
+ return (
149
+ f"{_with_unit(fmt_fn(left[name]), unit)} \N{RIGHTWARDS ARROW} "
150
+ f"{_with_unit(fmt_fn(right[name]), unit)}"
151
+ )
152
+
153
+ biggest = max(names, key=lambda nm: abs(deltas[nm]))
154
+ ups = sum(1 for d in deltas.values() if d > 0)
155
+ downs = sum(1 for d in deltas.values() if d < 0)
156
+ facts = [
157
+ f"largest change: {biggest} {_from_to(biggest)} ({_moved(biggest)})",
158
+ f"{ups} up, {downs} down, {len(names) - ups - downs} unchanged",
159
+ ]
160
+ for item in hl:
161
+ if item != biggest:
162
+ facts.append(f"{item}: {_from_to(item)} ({_moved(item)})")
163
+ # Alt text: the largest change and every highlighted item's.
164
+ alt_facts = [facts[0], *facts[2:]]
165
+ rest = [nm for nm in names if nm not in hl and nm != biggest]
166
+ if rest:
167
+ # One line for the items the takeaway does not name: "the other 4 changed by
168
+ # −2.1% to +2.9%" (points for "%" units; absolute when a percent is meaningless).
169
+ rels = [None if points else _relative_text(right[nm], left[nm], None) for nm in rest]
170
+ if not points and all(rels):
171
+ pct = sorted(rest, key=lambda nm: (right[nm] - left[nm]) / abs(left[nm]))
172
+ lo_t = _relative_text(right[pct[0]], left[pct[0]], None)
173
+ hi_t = _relative_text(right[pct[-1]], left[pct[-1]], None)
174
+ else:
175
+ by = sorted(rest, key=lambda nm: deltas[nm])
176
+ lo_t = _diff_with_unit(_delta_text(by[0]), unit)
177
+ hi_t = _diff_with_unit(_delta_text(by[-1]), unit)
178
+ who = "the other item" if len(rest) == 1 else f"the other {len(rest)}"
179
+ span = lo_t if len(rest) == 1 or lo_t == hi_t else f"{lo_t} to {hi_t}"
180
+ facts.append(f"{who} changed by {span}")
181
+
182
+ def _right_text(name: str, level: int, measure: _Measure, sizes: _Sizes) -> str:
183
+ """The label at the line's end. Level 0: "45.4 math (+16.8)" on one line; from
184
+ level 1 the name goes under "45.4 (+16.8)", wrapped onto two lines if long."""
185
+ head = fmt_fn(right[name])
186
+ if level == 0:
187
+ return f"{head} {name} ({_delta_text(name)})"
188
+ head = f"{head} ({_delta_text(name)})"
189
+ budget = max(measure.width_pt(head, sizes.small), 0.6 * _CHANGE_NAME_PT * sizes.scale)
190
+ lines = measure.wrap(name, budget, sizes.small)
191
+ if len(lines) > 2:
192
+ lines = [lines[0], " ".join(lines[1:])]
193
+ return "\n".join([head, *lines])
194
+
195
+ def _layout(cell_width_mm: float, measure: _Measure, sizes: _Sizes) -> tuple[int, float]:
196
+ """How the labels fit a cell this wide: the first level whose plot keeps its
197
+ minimum width (level 2 also drops the left-hand values), and the points needed."""
198
+ weight = "bold" # measure as the widest weight drawn
199
+ cell_pt = min(cell_width_mm, 92.0) * sizes.scale / PT_TO_MM
200
+ heads = [measure.width_pt(t, sizes.small, "bold") for t in labels]
201
+ plot_pt = max(_CHANGE_PLOT_MM * sizes.scale / PT_TO_MM, 0.5 * sum(heads) + 6.0)
202
+ left_pt = max(measure.width_pt(fmt_fn(left[nm]), sizes.small, weight) for nm in names)
203
+ need = 0.0
204
+ for level in (0, 1, 2):
205
+ right_pt = max(
206
+ measure.width_pt(line, sizes.small, weight)
207
+ for nm in names
208
+ for line in _right_text(nm, level, measure, sizes).split("\n")
209
+ )
210
+ need = (0.0 if level == 2 else left_pt + 6.0) + plot_pt + 6.0 + right_pt + 4.0
211
+ if need <= cell_pt:
212
+ return level, need
213
+ return 3, need
214
+
215
+ def _label_lines(cell_width_mm: float, measure: _Measure, sizes: _Sizes) -> int:
216
+ level, _need = _layout(cell_width_mm, measure, sizes)
217
+ if level == 0:
218
+ return 1
219
+ return max(
220
+ len(_right_text(nm, min(level, 2), measure, sizes).split("\n")) for nm in names
221
+ )
222
+
223
+ def _height(w: float, measure: _Measure, sizes: _Sizes, tight: bool) -> float:
224
+ lines = _label_lines(w, measure, sizes)
225
+ if lines == 1:
226
+ return max(30.0, 4.6 * len(names) + 10.0) if tight else max(38.0, 4.6 * len(names) + 12.0)
227
+ # Multi-line labels stack: each needs its lines of small text.
228
+ per = lines * 1.22 * sizes.small / sizes.scale * PT_TO_MM + 0.6
229
+ return max(30.0 if tight else 38.0, per * len(names) + (10.0 if tight else 12.0))
230
+
231
+ def _draw(ctx: _Ctx, ax: Axes) -> Callable[[], None]:
232
+ sz = ctx.sizes
233
+ theme = ctx.theme
234
+ level, need_pt = _layout(ctx.cell_width_mm, ctx.measure, sz)
235
+ if level == 3:
236
+ content_pt = (ctx.fig.bbox.width * ctx.pt_per_px) - 2 * _MARGIN_MM * sz.scale / PT_TO_MM
237
+ share = need_pt / content_pt
238
+ if share <= 1 / 3:
239
+ needs, example = "a third of the width", '[["a", "a", "b"]]'
240
+ elif share <= 1 / 2:
241
+ needs, example = "half the width", '[["a", "b"]]'
242
+ elif share <= 2 / 3:
243
+ needs, example = "two thirds of the width", '[["a", "b", "b"]]'
244
+ else:
245
+ needs, example = "the full width", '[["a"], ["b"]]'
246
+ raise ExplainError(
247
+ f"change() labels need at least {needs} ({need_pt * PT_TO_MM:.0f} mm, "
248
+ f"{100 * share:.0f}% of the figure) even with names wrapped and the left-hand "
249
+ "values dropped.",
250
+ fix_hint=f"Give the slopegraph at least {needs}, e.g. layout={example} with it "
251
+ "as panel b, or shorten the item names."
252
+ + (" No width fits: shorten the item names." if share > 1 else ""),
253
+ rule="panel_too_small",
254
+ )
255
+ lines = _label_lines(ctx.cell_width_mm, ctx.measure, sz)
256
+ accent = {name: col for name, col in ctx.colors.items() if name in names}
257
+ focus_mode = bool(hl or accent)
258
+ effects = ctx.line_effects()
259
+ _bare_axes(ax)
260
+ ax.xaxis.set_visible(False)
261
+ ax.yaxis.set_visible(False)
262
+ values = [*left.values(), *right.values()]
263
+ lo, hi = min(values), max(values)
264
+ span = (hi - lo) or abs(hi) or 1.0
265
+ ax.set_xlim(0.0, 1.0)
266
+ ax.set_ylim(lo - 0.05 * span, hi + 0.05 * span)
267
+ rail_col = theme.grid if theme.grid_style != "none" else theme.context_line
268
+ ax.vlines([0.0, 1.0], lo, hi, color=rail_col, linewidth=0.7, zorder=1)
269
+ for x_at, text, color in ((0.0, labels[0], theme.muted), (1.0, labels[1], theme.ink)):
270
+ ax.annotate(
271
+ _plain(text, theme),
272
+ (x_at, 1.0),
273
+ xycoords=("data", "axes fraction"),
274
+ xytext=(0.0, 5.0),
275
+ textcoords="offset points",
276
+ ha="center",
277
+ va="bottom",
278
+ fontsize=sz.small,
279
+ fontweight="bold",
280
+ color=color,
281
+ annotation_clip=False,
282
+ )
283
+ left_notes, right_notes = [], []
284
+ for item in names:
285
+ focus = item in accent
286
+ col = accent.get(item, theme.axis if not focus_mode else theme.context_line)
287
+ line_kw: dict[str, Any] = {
288
+ "color": col,
289
+ "linewidth": (
290
+ (theme.line_lw + 0.1 if focus else theme.context_line_lw + 0.1) * sz.scale
291
+ ),
292
+ "marker": "o",
293
+ "markersize": (3.6 if focus else 3.0) * sz.scale,
294
+ "markerfacecolor": col,
295
+ "markeredgecolor": theme.background,
296
+ "markeredgewidth": 0.6,
297
+ "zorder": 4 if focus else 2,
298
+ "clip_on": False,
299
+ "label": "_slope",
300
+ "solid_capstyle": theme.line_capstyle,
301
+ }
302
+ if effects is not None:
303
+ line_kw["path_effects"] = effects
304
+ ax.plot([0.0, 1.0], [left[item], right[item]], **line_kw)
305
+ text_color = ctx.text_color(col) if focus else theme.ink
306
+ weight = "bold" if focus else "normal"
307
+ if level < 2:
308
+ left_notes.append(
309
+ ax.annotate(
310
+ _plain(fmt_fn(left[item]), theme),
311
+ (0.0, left[item]),
312
+ xytext=(-6.0, 0.0),
313
+ textcoords="offset points",
314
+ ha="right",
315
+ va="center",
316
+ fontsize=sz.small,
317
+ color=text_color if focus else theme.muted,
318
+ fontweight=weight,
319
+ annotation_clip=False,
320
+ )
321
+ )
322
+ right_note = ax.annotate(
323
+ _plain(_right_text(item, level, ctx.measure, sz), theme),
324
+ (1.0, right[item]),
325
+ xytext=(6.0, 0.0),
326
+ textcoords="offset points",
327
+ ha="left",
328
+ va="center",
329
+ fontsize=sz.small,
330
+ color=text_color,
331
+ fontweight=weight,
332
+ annotation_clip=False,
333
+ )
334
+ right_note.set_linespacing(1.05)
335
+ right_notes.append(right_note)
336
+
337
+ def _finish() -> None:
338
+ renderer = ctx.fig.canvas.get_renderer()
339
+ box = ax.get_window_extent(renderer)
340
+ k = ctx.pt_per_px
341
+ for notes, x_at, source, dx, rows in (
342
+ (left_notes, 0.0, left, -6.0, 1),
343
+ (right_notes, 1.0, right, 6.0, lines),
344
+ ):
345
+ if not notes:
346
+ continue
347
+ ys = np.array([ax.transData.transform((x_at, source[nm]))[1] * k for nm in names])
348
+ # A wrapped label's first line (its value) sits level with the line's end.
349
+ half = 0.5 * (rows - 1) * sz.small * 1.1
350
+ placed = _relax_positions_pt(
351
+ ys - half,
352
+ sz.small * (1.22 + 1.1 * (rows - 1)),
353
+ box.y0 * k + half,
354
+ box.y1 * k - half,
355
+ )
356
+ for note, y0, y1 in zip(notes, ys, placed, strict=True):
357
+ note.set_position((dx, float(y1 - y0)))
358
+
359
+ return _finish
360
+
361
+ def _narrow(ctx: _Ctx, ax: Axes, rect: Bbox) -> list[tuple[Axes, Bbox]]:
362
+ """A slopegraph reads by steepness, so it never spans a full-width row."""
363
+ limit = 92.0 * ctx.sizes.scale * float(ctx.fig.dpi) / 25.4
364
+ return [(ax, Bbox.from_extents(rect.x0, rect.y0, min(rect.x1, rect.x0 + limit), rect.y1))]
365
+
366
+ return Panel(
367
+ kind="change",
368
+ alt_facts=alt_facts,
369
+ title=title,
370
+ label=label,
371
+ unit=unit,
372
+ spec=_base_spec(
373
+ title,
374
+ label,
375
+ unit,
376
+ before=dict(left),
377
+ after=dict(right),
378
+ labels=list(labels),
379
+ highlight=hl or None,
380
+ fmt=fmt,
381
+ ),
382
+ facts=facts,
383
+ describe=f"Slopegraph of {label or 'values'} for {len(names)} items, {labels[0]} to {labels[1]}",
384
+ _height_mm=lambda w, m, sizes, _t: _height(w, m, sizes, tight=False),
385
+ _min_height_mm=lambda w, m, sizes, _t: _height(w, m, sizes, tight=True),
386
+ _frames=_narrow,
387
+ _draw=_draw,
388
+ color_items=tuple(names),
389
+ color_focus=tuple(hl),
390
+ color_mode="highlight" if hl else "uniform",
391
+ uses_default=False, # without highlight every slope is the same neutral grey
392
+ )