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,1268 @@
1
+ """distribution() and histogram() forms 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 import patheffects
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.ticker import (
12
+ FuncFormatter,
13
+ MaxNLocator,
14
+ )
15
+ from matplotlib.transforms import Bbox
16
+
17
+ from ..themes import (
18
+ Theme,
19
+ )
20
+ from .core import (
21
+ MAX_COMPARE_ITEMS,
22
+ MAX_GROUPS,
23
+ ExplainError,
24
+ Panel,
25
+ _base_spec,
26
+ _baseline_name,
27
+ _cover_with_ticks,
28
+ _Ctx,
29
+ _diff_with_unit,
30
+ _fold_unit,
31
+ _formatter,
32
+ _guarded,
33
+ _has_items,
34
+ _inline_unit,
35
+ _is_number,
36
+ _is_one_dimensional,
37
+ _is_strict,
38
+ _jsonable,
39
+ _keep_inside_x,
40
+ _measure_text,
41
+ _names,
42
+ _narrow_log_ticks,
43
+ _pairs,
44
+ _plain,
45
+ _range_with_unit,
46
+ _ratio_text,
47
+ _record_adjustment,
48
+ _reference_line,
49
+ _signed,
50
+ _Sizes,
51
+ _small_n_caution,
52
+ _tick_label,
53
+ _value_axis,
54
+ _values_array,
55
+ _vs_text,
56
+ _with_unit,
57
+ )
58
+
59
+ # --------------------------------------------------------------------------- #
60
+ # distribution
61
+ # --------------------------------------------------------------------------- #
62
+
63
+
64
+ def _far_values(arr: np.ndarray, log: bool = False) -> np.ndarray:
65
+ """Values more than 4 robust s.d. (1.4826·MAD) from the median; groups with n >= 5 only.
66
+
67
+ On a log axis the distances are measured in log space, as the reader sees them.
68
+ """
69
+ if arr.size < 5:
70
+ return np.empty(0)
71
+ scaled = np.log10(arr) if log else arr
72
+ med = float(np.median(scaled))
73
+ dist = np.abs(scaled - med)
74
+ mad = float(np.median(dist))
75
+ if mad == 0:
76
+ return np.empty(0)
77
+ far = dist > 4.0 * 1.4826 * mad
78
+ return arr[far][np.argsort(-dist[far])]
79
+
80
+
81
+ def _separation_fact(
82
+ h: str,
83
+ a: np.ndarray,
84
+ other: str,
85
+ b: np.ndarray,
86
+ b_far: np.ndarray,
87
+ value_fmt: Callable[[float], str],
88
+ *,
89
+ stat: str,
90
+ ) -> str:
91
+ """Whether two groups separate, robust to one stray value.
92
+
93
+ Every value beyond every other ("every A value is above every B value"); else all
94
+ but a few (at most max(1, 20% of n)) of one group beyond the other's whole range;
95
+ else how many of ``h``'s values lie within ``other``'s range (without its far values).
96
+ """
97
+ up = (np.median(a) if stat == "median" else a.mean()) >= (
98
+ np.median(b) if stat == "median" else b.mean()
99
+ )
100
+ if (up and a.min() > b.max()) or (not up and a.max() < b.min()):
101
+ edge_a, edge_b = (a.min(), b.max()) if up else (a.max(), b.min())
102
+ return (
103
+ f"every {h} value is {'above' if up else 'below'} every {other} value "
104
+ f"({h} {'lowest' if up else 'highest'} {value_fmt(float(edge_a))}, "
105
+ f"{other} {'highest' if up else 'lowest'} {value_fmt(float(edge_b))})"
106
+ )
107
+ side = "above" if up else "below"
108
+ options = []
109
+ # Groups X, Y with X on ``side`` of Y: X values not beyond all of Y are the exceptions.
110
+ flipped = "below" if up else "above"
111
+ for x_name, x, y_name, y, x_side in ((h, a, other, b, side), (other, b, h, a, flipped)):
112
+ exceptions = x[x <= y.max()] if x_side == "above" else x[x >= y.min()]
113
+ if exceptions.size <= max(1, int(0.2 * x.size)) and exceptions.size < x.size:
114
+ options.append((exceptions.size / x.size, x_name, x, y_name, x_side, exceptions))
115
+ if options:
116
+ _, x_name, x, y_name, x_side, exceptions = min(options, key=lambda o: o[0])
117
+ listed = ", ".join(value_fmt(float(v)) for v in exceptions[:3])
118
+ return (
119
+ f"all but {exceptions.size} of {x.size} {x_name} values lie {x_side} every "
120
+ f"{y_name} value (the exception{'s' if exceptions.size > 1 else ''}: {listed})"
121
+ )
122
+ core = b if not b_far.size else b[~np.isin(b, b_far)]
123
+ inside = int(((a >= core.min()) & (a <= core.max())).sum())
124
+ excluded = (
125
+ f" (without its {b_far.size} far value{'s' if b_far.size > 1 else ''})" if b_far.size else ""
126
+ )
127
+ return (
128
+ f"{h} and {other} overlap: {inside} of {a.size} {h} values lie within "
129
+ f"the {other} range{excluded}"
130
+ )
131
+
132
+
133
+ def _prob_superiority(a: np.ndarray, b: np.ndarray) -> float:
134
+ """Empirical probability of superiority P(A > B) + 0.5 * P(A == B) over all pairs."""
135
+ b_sorted = np.sort(b)
136
+ lo = np.searchsorted(b_sorted, a, side="left")
137
+ hi = np.searchsorted(b_sorted, a, side="right")
138
+ return float((lo.sum() + 0.5 * (hi - lo).sum()) / (a.size * b.size))
139
+
140
+
141
+ def _wilkinson_stack(sorted_vals: np.ndarray, bin_width: float) -> list[tuple[float, int]]:
142
+ """Bin sorted 1-D values into non-overlapping Wilkinson dot columns ``(center, count)``."""
143
+ if sorted_vals.size == 0:
144
+ return []
145
+ bw = max(float(bin_width), 1e-12)
146
+ raw_bins: list[list[float]] = [[float(sorted_vals[0])]]
147
+ anchor = float(sorted_vals[0])
148
+ for v in sorted_vals[1:]:
149
+ fv = float(v)
150
+ if fv - anchor <= bw:
151
+ raw_bins[-1].append(fv)
152
+ else:
153
+ raw_bins.append([fv])
154
+ anchor = fv
155
+ # Merge any adjacent columns whose midpoints still sit closer than bin_width.
156
+ merged: list[list[float]] = [raw_bins[0]]
157
+ for grp in raw_bins[1:]:
158
+ prev = merged[-1]
159
+ c_prev = 0.5 * (prev[0] + prev[-1])
160
+ c_curr = 0.5 * (grp[0] + grp[-1])
161
+ if c_curr - c_prev < bw:
162
+ merged[-1] = prev + grp
163
+ else:
164
+ merged.append(grp)
165
+ return [(0.5 * (grp[0] + grp[-1]), len(grp)) for grp in merged]
166
+
167
+
168
+ _HIST_ESTIMATORS = frozenset({"auto", "fd", "doane", "scott", "stone", "rice", "sturges", "sqrt"})
169
+ MAX_HIST_GROUPS = 4
170
+
171
+
172
+ def _histogram_edges(
173
+ everything: np.ndarray,
174
+ bins: int | str | Sequence[float],
175
+ log: bool,
176
+ ) -> tuple[np.ndarray, int | str | list[float], str]:
177
+ """Validate ``bins`` and return ``(edges, spec_value, width_summary)``."""
178
+ lo, hi = float(everything.min()), float(everything.max())
179
+ if isinstance(bins, bool):
180
+ raise ExplainError(
181
+ "distribution(bins) must be 'auto', an integer count, or a list of bin edges.",
182
+ fix_hint='Pass bins="auto", bins=15, or bins=[0, 10, 20, 50].',
183
+ )
184
+ if isinstance(bins, (int, np.integer)):
185
+ count = int(bins)
186
+ if not 2 <= count <= 60:
187
+ raise ExplainError(
188
+ f"distribution(bins={count}) is outside the readable range (2 to 60).",
189
+ fix_hint='Use between 2 and 60 bins, or bins="auto".',
190
+ )
191
+ if log:
192
+ if hi <= lo:
193
+ edges = np.geomspace(lo * 0.8, hi * 1.25, count + 1)
194
+ else:
195
+ edges = np.geomspace(lo, hi, count + 1)
196
+ return edges, count, f"{count} log-spaced bins"
197
+ if hi <= lo:
198
+ edges = np.linspace(lo - 0.5, hi + 0.5, count + 1)
199
+ else:
200
+ edges = np.linspace(lo, hi, count + 1)
201
+ return edges, count, f"{count} bins"
202
+ if isinstance(bins, str):
203
+ key = bins.strip().lower()
204
+ if key not in _HIST_ESTIMATORS:
205
+ raise ExplainError(
206
+ f"distribution(bins={bins!r}) is not a recognised binning rule.",
207
+ fix_hint=f"Use bins='auto', an integer (2–60), or one of: {', '.join(sorted(_HIST_ESTIMATORS))}.",
208
+ )
209
+ if log:
210
+ log_edges = np.histogram_bin_edges(np.log10(everything), bins=key)
211
+ count = max(5, min(24, len(log_edges) - 1))
212
+ if hi <= lo:
213
+ edges = np.geomspace(lo * 0.8, hi * 1.25, count + 1)
214
+ else:
215
+ edges = np.geomspace(lo, hi, count + 1)
216
+ return edges, key, f"{count} log-spaced bins"
217
+ edges = np.histogram_bin_edges(everything, bins=key)
218
+ if len(edges) - 1 > 28:
219
+ edges = np.linspace(lo, hi, 25)
220
+ elif len(edges) - 1 < 3 and hi > lo:
221
+ edges = np.linspace(lo, hi, 6)
222
+ return edges, key, f"{len(edges) - 1} bins"
223
+ if isinstance(bins, (Sequence, np.ndarray)):
224
+ arr = _values_array(bins, "distribution(bins)")
225
+ if arr.size < 3 or arr.size > 61:
226
+ raise ExplainError(
227
+ f"distribution(bins) needs 3 to 61 edges (2 to 60 bins), got {arr.size}.",
228
+ fix_hint='Pass at least 3 increasing edges, or bins="auto".',
229
+ )
230
+ if not np.all(np.isfinite(arr)) or not np.all(np.diff(arr) > 0):
231
+ raise ExplainError(
232
+ "distribution(bins) edges must be finite and strictly increasing.",
233
+ fix_hint="Sort and deduplicate the bin edges.",
234
+ )
235
+ if log and float(arr.min()) <= 0:
236
+ raise ExplainError(
237
+ "distribution(log=True) needs strictly positive bin edges.",
238
+ fix_hint="Use positive bin edges or drop log=True.",
239
+ )
240
+ spec_edges = [float(v) for v in arr]
241
+ return arr, spec_edges, f"{arr.size - 1} custom bins"
242
+ raise ExplainError(
243
+ f"distribution(bins) got unsupported type {type(bins).__name__}.",
244
+ fix_hint='Pass bins="auto", an integer (2–60), or a sorted list of edges.',
245
+ )
246
+
247
+
248
+ @_guarded("distribution")
249
+ def distribution(
250
+ groups: Mapping[str, Sequence[float]] | Sequence[float] | Sequence[Mapping[str, Any]],
251
+ *,
252
+ group: str | None = None,
253
+ value: str | None = None,
254
+ title: str | None = None,
255
+ label: str | None = None,
256
+ unit: str | None = None,
257
+ highlight: str | Sequence[str] | None = None,
258
+ baseline: str | None = None,
259
+ reference: float | tuple[float, str] | None = None,
260
+ log: bool = False,
261
+ stat: str = "median",
262
+ bins: int | str | Sequence[float] | None = None,
263
+ fmt: str | None = None,
264
+ mode: str = "dots",
265
+ quantiles: int = 20,
266
+ ) -> Panel:
267
+ """How are values spread within groups? Every observation as a dot, quantile dotplot, or histogram.
268
+
269
+ ``groups`` maps a group name to its raw observations (or pass one list/array
270
+ for a single variable, or row-shaped data / DataFrame with ``group=`` and
271
+ ``value=``). By default (``mode="dots"``) every observation is drawn as a dot with
272
+ a ``stat="median"`` (median and middle half / IQR) or ``stat="mean"`` (mean
273
+ and \N{PLUS-MINUS SIGN} 1 s.d.) mark. Pass ``mode="quantile"`` (with optional
274
+ ``quantiles=20``, 5–50) for Wilkinson-stacked countable quantile dotplots
275
+ (Kay & Hullman) where each dot represents ``100 / quantiles``% probability.
276
+ Pass ``bins="auto"`` (an integer 2–60, or explicit edges) — or call the alias
277
+ :func:`histogram` — to draw a binned histogram (single panel, or shared-axis
278
+ stacked small multiples for up to 4 groups). ``baseline`` names the reference
279
+ group (a control, "before"): drawn in ink, with every highlighted (or every
280
+ other) group stated against it, including pairwise superiority probability
281
+ ``P(group > baseline)``.
282
+ """
283
+ if stat not in {"median", "mean"}:
284
+ raise ExplainError(
285
+ f"distribution(stat={stat!r}) is not a summary this form draws.",
286
+ fix_hint='Use stat="median" (median and middle half) or stat="mean" (mean and '
287
+ "\N{PLUS-MINUS SIGN} 1 s.d.).",
288
+ )
289
+ if not isinstance(mode, str) or mode not in {"dots", "quantile"}:
290
+ raise ExplainError(
291
+ f"distribution(mode={mode!r}) is not a recognised mode.",
292
+ fix_hint='Use mode="dots" (raw observations) or mode="quantile" (stacked countable quantile dotplot).',
293
+ )
294
+ if (
295
+ isinstance(quantiles, bool)
296
+ or not isinstance(quantiles, (int, np.integer))
297
+ or not (5 <= int(quantiles) <= 50)
298
+ ):
299
+ raise ExplainError(
300
+ f"distribution(quantiles={quantiles!r}) must be an integer between 5 and 50.",
301
+ fix_hint="Pass quantiles=20 (each dot = 5%) or another integer from 5 to 50.",
302
+ )
303
+ q = int(quantiles)
304
+ if mode == "quantile" and bins is not None:
305
+ raise ExplainError(
306
+ 'distribution(mode="quantile") cannot be combined with bins=.',
307
+ fix_hint='Drop bins= to draw a quantile dotplot, or use mode="dots" with bins= for a histogram.',
308
+ )
309
+ from .._tabular import resolve_distribution_table
310
+
311
+ tabular = resolve_distribution_table(
312
+ groups,
313
+ group=group,
314
+ value=value,
315
+ form="distribution",
316
+ )
317
+ if tabular is not None:
318
+ groups = tabular
319
+ if _has_items(groups) and not _is_one_dimensional(groups):
320
+ raw = {str(k): v for k, v in _pairs(groups)}
321
+ elif isinstance(groups, (str, bytes)) or _is_number(groups) or groups is None:
322
+ raise ExplainError(
323
+ "distribution(groups) must map group names to lists of observations.",
324
+ fix_hint='e.g. {"control": [4.1, 3.9, 4.4, ...], "treated": [...]}.',
325
+ )
326
+ else:
327
+ raw = {"": groups}
328
+ data: dict[str, np.ndarray] = {}
329
+ dropped: dict[str, int] = {}
330
+ given: dict[str, np.ndarray] = {}
331
+ for name, values in raw.items():
332
+ if _is_number(values) or values is None or isinstance(values, (str, bytes)):
333
+ raise ExplainError(
334
+ f"distribution(groups[{name!r}]) is {values!r}, not a list of observations.",
335
+ fix_hint="distribution() shows raw observations; for one summary number per "
336
+ "group use compare() (with error= for an interval).",
337
+ )
338
+ arr = _values_array(values, f"distribution(groups[{name!r}])")
339
+ given[name] = arr
340
+ dropped[name] = int((~np.isfinite(arr)).sum())
341
+ arr = arr[np.isfinite(arr)]
342
+ if arr.size < 3:
343
+ raise ExplainError(
344
+ f"distribution(groups[{name!r}]) has {arr.size} finite values; a spread needs >= 3.",
345
+ fix_hint="Use compare() for one or two values per item.",
346
+ )
347
+ data[name] = arr
348
+ if not data:
349
+ raise ExplainError("distribution(groups) is empty.", fix_hint="Pass at least one group.")
350
+ names = list(data)
351
+ group_limit = MAX_HIST_GROUPS if bins is not None else MAX_GROUPS
352
+ if len(names) > group_limit:
353
+ if not _is_strict():
354
+ req_hl = (
355
+ [highlight]
356
+ if isinstance(highlight, str)
357
+ else ([str(h) for h in highlight] if highlight is not None else [])
358
+ )
359
+ keep = [nm for nm in req_hl if nm in data]
360
+ if baseline is not None and str(baseline) in data and str(baseline) not in keep:
361
+ keep.append(str(baseline))
362
+ for nm in names:
363
+ if len(keep) >= group_limit:
364
+ break
365
+ if nm not in keep:
366
+ keep.append(nm)
367
+ keep_set = set(keep)
368
+ data = {nm: data[nm] for nm in names if nm in keep_set}
369
+ given = {nm: given[nm] for nm in names if nm in keep_set}
370
+ dropped = {nm: dropped[nm] for nm in names if nm in keep_set}
371
+ _record_adjustment(f"distribution(): trimmed {len(names)} groups to {len(data)}")
372
+ names = list(data)
373
+ elif bins is None:
374
+ raise ExplainError(
375
+ f"distribution() got {len(names)} groups; more than {MAX_GROUPS} rows of dots blur together.",
376
+ fix_hint=f"distribution() takes at most {MAX_GROUPS} groups: keep the groups the "
377
+ f"takeaway compares, or compare() their medians (up to {MAX_COMPARE_ITEMS} items, "
378
+ "with error= for an interval).",
379
+ rule="too_many_items",
380
+ )
381
+ hl = _names(highlight, names)
382
+ base = _baseline_name(baseline, names, hl, "distribution")
383
+ ref = _reference_line(reference, "distribution(reference)")
384
+ everything = np.concatenate(list(data.values()))
385
+ given_unit = unit
386
+ # Raw ratios (fold changes) read as ratios: "median 2.46×", not "2.46 fold".
387
+ if _fold_unit(unit, label, log and float(everything.min()) > 0):
388
+ unit = "\N{MULTIPLICATION SIGN}"
389
+ if log and (everything.min() <= 0 or (ref is not None and ref[0] <= 0)):
390
+ raise ExplainError(
391
+ "distribution(log=True) needs strictly positive values.",
392
+ fix_hint="Drop log=True or remove non-positive values.",
393
+ )
394
+ if stat == "mean":
395
+ stats = {}
396
+ for nm, arr in data.items():
397
+ m, sd = float(arr.mean()), float(arr.std(ddof=1))
398
+ stats[nm] = (m - sd, m, m + sd)
399
+ else:
400
+ stats = {
401
+ nm: tuple(float(q) for q in np.percentile(arr, [25, 50, 75]))
402
+ for nm, arr in data.items()
403
+ }
404
+ fmt_fn = _formatter([q for trio in stats.values() for q in trio], fmt, unit=unit, log=log)
405
+ # Ranges, far values and separation edges share the centres' digits (whole numbers
406
+ # stay whole: "lowest 91", not "91.0").
407
+ whole = all(float(v).is_integer() for v in everything)
408
+ range_fmt = _formatter(list(everything), fmt, unit=unit, log=log) if whole else fmt_fn
409
+ facts = []
410
+ for nm in names:
411
+ lo_q, mid, hi_q = stats[nm]
412
+ spread = (
413
+ f"\N{PLUS-MINUS SIGN} 1 s.d. {_range_with_unit(fmt_fn(lo_q), fmt_fn(hi_q), unit)}"
414
+ if stat == "mean"
415
+ else f"middle half {_range_with_unit(fmt_fn(lo_q), fmt_fn(hi_q), unit)}"
416
+ )
417
+ arr = data[nm]
418
+ text = (
419
+ f"{nm or (label or 'values')}: {stat} {_with_unit(fmt_fn(mid), unit)}, {spread}, "
420
+ f"range {_range_with_unit(range_fmt(float(arr.min())), range_fmt(float(arr.max())), unit)}, "
421
+ f"n={arr.size}"
422
+ )
423
+ if dropped[nm]:
424
+ text += f"; {dropped[nm]} missing value{'s' if dropped[nm] > 1 else ''} dropped"
425
+ facts.append(text)
426
+ caution = _small_n_caution(
427
+ {nm or (label or "values"): data[nm].size for nm in names},
428
+ "quartiles are not meaningful" if stat == "median" else "the s.d. is a rough estimate",
429
+ )
430
+ if caution:
431
+ facts.append(caution)
432
+ outliers = {nm: _far_values(data[nm], log) for nm in names}
433
+ for nm in names:
434
+ far = outliers[nm]
435
+ if far.size:
436
+ shown_far = ", ".join(_with_unit(range_fmt(float(v)), unit) for v in far[:5])
437
+ more = f" and {far.size - 5} more" if far.size > 5 else ""
438
+ word = "value" if far.size == 1 else "values"
439
+ facts.append(
440
+ f"{nm or (label or 'values')}: {far.size} {word} far from the rest: "
441
+ f"{shown_far}{more} (median {_with_unit(fmt_fn(float(np.median(data[nm]))), unit)})"
442
+ )
443
+ # Which pairs are stated: each group against the baseline; else among the
444
+ # highlighted groups (each pair once); a lone highlight against every other group.
445
+ pairs: list[tuple[str, str]] = []
446
+ if base is not None:
447
+ pairs = [(nm, base) for nm in (hl or [nm for nm in names if nm != base])][:6]
448
+ elif len(hl) >= 2:
449
+ pairs = [(a, b) for i, a in enumerate(hl) for b in hl[i + 1 :]]
450
+ elif hl:
451
+ pairs = [(hl[0], other) for other in names if other != hl[0]]
452
+ first_pair_fact = len(facts)
453
+ if log:
454
+ # On a log axis groups differ by factors: state ratios, not differences.
455
+ for h, other in pairs:
456
+ ratio = _ratio_text(stats[h][1] / stats[other][1])
457
+ facts.append(f"{h} is {ratio} {other} ({stat})")
458
+ elif pairs:
459
+ diffs = [(h, other, stats[h][1] - stats[other][1]) for h, other in pairs]
460
+ diff_fmt = _formatter([d for _, _, d in diffs], fmt, unit=unit)
461
+ signed_spread = float(everything.min()) < 0 < float(everything.max())
462
+ for h, other, _d in diffs:
463
+ if base is not None:
464
+ vs = _vs_text(
465
+ stats[h][1],
466
+ stats[other][1],
467
+ unit=unit,
468
+ diff_fmt=diff_fmt,
469
+ relative=not signed_spread,
470
+ )
471
+ facts.append(f"{h} vs {other}: {stat} {vs}")
472
+ continue
473
+ shown = _diff_with_unit(_signed(diff_fmt(_d)), unit)
474
+ if stats[h][1] > 0 and stats[other][1] > 0:
475
+ shown += f" ({_ratio_text(stats[h][1] / stats[other][1])})"
476
+ facts.append(f"{h} \N{MINUS SIGN} {other}: {stat} {shown}")
477
+ pair_facts = facts[first_pair_fact:]
478
+ # Whether every observation of one group lies beyond every one of the other:
479
+ # the check behind "every treated cell beats every control cell".
480
+ for h, other in pairs:
481
+ facts.append(
482
+ _separation_fact(
483
+ h,
484
+ data[h],
485
+ other,
486
+ data[other],
487
+ outliers[other],
488
+ lambda v: _with_unit(range_fmt(v), unit),
489
+ stat=stat,
490
+ )
491
+ )
492
+ if base is not None:
493
+ for h, other in pairs:
494
+ if data[h].size >= 3 and data[other].size >= 3:
495
+ p_sup = _prob_superiority(data[h], data[other])
496
+ facts.append(f"P({h} > {other}) = {100.0 * p_sup:.0f}%")
497
+ qvals: dict[str, np.ndarray] = {}
498
+ if mode == "quantile":
499
+ probs = (np.arange(q, dtype=float) + 0.5) / q
500
+ qvals = {nm: np.quantile(data[nm], probs) for nm in names}
501
+ if ref is not None and bins is None:
502
+ ref_u = _with_unit(_formatter([ref[0]], log=log)(ref[0]), unit)
503
+ ref_tag = f" ({ref[1]})" if ref[1] else ""
504
+ for nm in names:
505
+ tag = nm or (label or "values")
506
+ if mode == "quantile":
507
+ k_above = int((qvals[nm] > ref[0]).sum())
508
+ facts.append(
509
+ f"{tag}: {k_above} of {q} quantiles ({100.0 * k_above / q:.0f}%) above "
510
+ f"{ref_u}{ref_tag}"
511
+ )
512
+ else:
513
+ arr = data[nm]
514
+ above = int((arr > ref[0]).sum())
515
+ facts.append(
516
+ f"{tag}: {100.0 * above / arr.size:.0f}% of observations above "
517
+ f"{ref_u}{ref_tag} ({above} of {arr.size})"
518
+ )
519
+ any_spread = any(a.size >= 5 for a in data.values())
520
+ # Alt text: every group's centre (or the highlighted groups and the baseline), then
521
+ # how they compare; never only the first group.
522
+ paired = {nm for pair in pairs for nm in pair} | set(hl)
523
+ told = [nm for nm in names if nm in paired] or names
524
+ alt_facts = [
525
+ f"{nm or (label or 'values')}: {stat} {_with_unit(fmt_fn(stats[nm][1]), unit)}"
526
+ for nm in told
527
+ ]
528
+ alt_facts += pair_facts
529
+
530
+ if bins is not None:
531
+ if len(names) > MAX_HIST_GROUPS:
532
+ raise ExplainError(
533
+ f"Binned distribution() got {len(names)} groups; more than {MAX_HIST_GROUPS} "
534
+ "stacked histograms crowd a chat figure.",
535
+ fix_hint=f"Keep at most {MAX_HIST_GROUPS} groups for histograms, or omit bins= "
536
+ f"for dot strips (up to {MAX_GROUPS} groups).",
537
+ rule="too_many_items",
538
+ )
539
+ edges, bins_spec, bins_desc = _histogram_edges(everything, bins, log)
540
+ hists = {nm: np.histogram(data[nm], bins=edges)[0] for nm in names}
541
+ max_count = max(int(c.max()) for c in hists.values()) if hists else 1
542
+ widths = np.diff(edges)
543
+ uniform_width = (not log) and bool(np.allclose(widths, widths[0], rtol=1e-4))
544
+ edge_fmt = _formatter(list(edges), fmt, unit=unit, log=log)
545
+ if uniform_width:
546
+ w_fmt = _formatter([float(widths[0])], fmt, unit=unit)
547
+ bin_note = f"{len(edges) - 1} bins (width {_with_unit(w_fmt(float(widths[0])), unit)})"
548
+ else:
549
+ bin_note = bins_desc
550
+ facts.append(f"binned into {bin_note}")
551
+ for nm in names:
552
+ counts = hists[nm]
553
+ peak_i = int(np.argmax(counts))
554
+ peak_c = int(counts[peak_i])
555
+ pct = 100.0 * peak_c / max(1, data[nm].size)
556
+ lo_e = edge_fmt(float(edges[peak_i]))
557
+ hi_e = edge_fmt(float(edges[peak_i + 1]))
558
+ bin_span = _range_with_unit(lo_e, hi_e, unit)
559
+ tag = nm or (label or "values")
560
+ facts.append(f"{tag}: peak bin {bin_span} ({peak_c} of {data[nm].size}, {pct:.0f}%)")
561
+ if ref is not None:
562
+ above = int((data[nm] > ref[0]).sum())
563
+ below = int((data[nm] < ref[0]).sum())
564
+ ref_u = _with_unit(_formatter([ref[0]], log=log)(ref[0]), unit)
565
+ ref_tag = f" ({ref[1]})" if ref[1] else ""
566
+ facts.append(
567
+ f"{tag}: {100.0 * above / data[nm].size:.0f}% above {ref_u}{ref_tag} "
568
+ f"({above} of {data[nm].size}; {below} below)"
569
+ )
570
+
571
+ x_lo = float(edges[0])
572
+ x_hi = float(edges[-1])
573
+ if ref is not None:
574
+ x_lo = min(x_lo, ref[0])
575
+ x_hi = max(x_hi, ref[0])
576
+
577
+ def _setup_hist_axes(
578
+ ax_h: Axes,
579
+ sz: _Sizes,
580
+ theme: Theme,
581
+ *,
582
+ show_x: bool,
583
+ nbins_y: int,
584
+ cell_w_mm: float,
585
+ ) -> None:
586
+ if log:
587
+ ax_h.set_xscale("log")
588
+ _value_axis(ax_h, sz, theme, axis="y", nbins=nbins_y)
589
+ ax_h.yaxis.set_major_locator(MaxNLocator(nbins=nbins_y, integer=True))
590
+ ax_h.spines["left"].set_visible(False)
591
+ ax_h.spines["top"].set_visible(False)
592
+ ax_h.spines["right"].set_visible(False)
593
+ ax_h.spines["bottom"].set_visible(not theme.hide_spines)
594
+ if not theme.hide_spines:
595
+ ax_h.spines["bottom"].set_color(theme.axis)
596
+ ax_h.spines["bottom"].set_linewidth(theme.axis_lw)
597
+ ax_h.tick_params(
598
+ axis="x",
599
+ length=theme.tick_length if show_x else 0.0,
600
+ width=theme.tick_width,
601
+ color=theme.axis,
602
+ labelsize=sz.small,
603
+ labelcolor=theme.muted,
604
+ labelbottom=show_x,
605
+ )
606
+ ax_h.set_ylim(0, max(1.0, max_count * 1.14))
607
+ if log:
608
+ ax_h.set_xlim(
609
+ *_narrow_log_ticks(
610
+ ax_h.xaxis,
611
+ x_lo / 1.06,
612
+ x_hi * 1.06,
613
+ theme.minus_sign,
614
+ extend=False,
615
+ data_hi=x_hi,
616
+ )
617
+ )
618
+ else:
619
+ span = (x_hi - x_lo) or abs(x_hi) or 1.0
620
+ ax_h.set_xlim(x_lo - 0.02 * span, x_hi + 0.02 * span)
621
+ ax_h.xaxis.set_major_locator(
622
+ MaxNLocator(nbins=6 if cell_w_mm >= 100 else 4, steps=[1, 2, 2.5, 5, 10])
623
+ )
624
+ ax_h.xaxis.set_major_formatter(
625
+ FuncFormatter(
626
+ lambda v, _p, m=theme.minus_sign, a=ax_h.xaxis: _tick_label(v, m, a)
627
+ )
628
+ )
629
+ if show_x:
630
+ x_title = _measure_text(label, unit)
631
+ if x_title:
632
+ ax_h.set_xlabel(
633
+ _plain(x_title, theme),
634
+ fontsize=sz.small,
635
+ color=theme.muted,
636
+ labelpad=3,
637
+ )
638
+
639
+ def _draw_hist_bars(
640
+ ctx: _Ctx, ax_h: Axes, nm: str, accent_map: Mapping[str, str], sz: _Sizes, theme: Theme
641
+ ) -> None:
642
+ if nm == base:
643
+ col = ctx.colors.get(nm, theme.ink)
644
+ else:
645
+ col = accent_map.get(
646
+ nm, theme.context_fill if (hl or accent_map) else ctx.default_color
647
+ )
648
+ edge_col = theme.bar_edgecolor or theme.background
649
+ edge_lw = theme.bar_edge_lw if theme.bar_edgecolor else 0.65
650
+ ax_h.bar(
651
+ edges[:-1],
652
+ hists[nm],
653
+ width=widths,
654
+ align="edge",
655
+ color=col,
656
+ edgecolor=edge_col,
657
+ linewidth=edge_lw,
658
+ alpha=0.88,
659
+ zorder=2,
660
+ )
661
+ med = stats[nm][1]
662
+ ax_h.axvline(
663
+ med,
664
+ color=theme.ink,
665
+ linewidth=1.1 * sz.scale,
666
+ linestyle="--",
667
+ zorder=4,
668
+ )
669
+ if ref is not None:
670
+ ax_h.axvline(
671
+ ref[0],
672
+ color=theme.muted,
673
+ linewidth=0.85 * sz.scale,
674
+ linestyle=(0, (3, 2)),
675
+ zorder=3,
676
+ )
677
+
678
+ single_measure = (
679
+ f"Count (n={data[names[0]].size}); {bin_note}; dashed: {stat}"
680
+ if len(names) == 1
681
+ else f"Count per group; {bin_note}; dashed: {stat}"
682
+ )
683
+
684
+ if len(names) == 1:
685
+ nm0 = names[0]
686
+
687
+ def _draw_single_hist(ctx: _Ctx, ax: Axes) -> Callable[[], None] | None:
688
+ sz = ctx.sizes
689
+ theme = ctx.theme
690
+ accent = {
691
+ name: col for name, col in ctx.colors.items() if name in names and name != base
692
+ }
693
+ _setup_hist_axes(
694
+ ax, sz, theme, show_x=True, nbins_y=4, cell_w_mm=ctx.cell_width_mm
695
+ )
696
+ _draw_hist_bars(ctx, ax, nm0, accent, sz, theme)
697
+ med = stats[nm0][1]
698
+ top_notes: list[Any] = []
699
+ med_text = f"{stat} {_with_unit(fmt_fn(med), unit)}"
700
+ med_note = ax.annotate(
701
+ _plain(med_text, theme),
702
+ (med, 1.0),
703
+ xycoords=("data", "axes fraction"),
704
+ xytext=(0.0, 3.0),
705
+ textcoords="offset points",
706
+ ha="center",
707
+ va="bottom",
708
+ fontsize=sz.small,
709
+ fontweight="bold",
710
+ color=theme.ink,
711
+ annotation_clip=False,
712
+ )
713
+ top_notes.append(med_note)
714
+ ref_note = None
715
+ if ref is not None and ref[1]:
716
+ ref_note = ax.annotate(
717
+ _plain(ref[1], theme),
718
+ (ref[0], 1.0),
719
+ xycoords=("data", "axes fraction"),
720
+ xytext=(0.0, 3.0),
721
+ textcoords="offset points",
722
+ ha="center",
723
+ va="bottom",
724
+ fontsize=sz.small,
725
+ color=theme.muted,
726
+ annotation_clip=False,
727
+ )
728
+ top_notes.append(ref_note)
729
+
730
+ def _finish_hist() -> None:
731
+ for note in top_notes:
732
+ _keep_inside_x(ctx, ax, note)
733
+ if ref_note is not None:
734
+ renderer = ctx.fig.canvas.get_renderer()
735
+ b0 = med_note.get_window_extent(renderer)
736
+ b1 = ref_note.get_window_extent(renderer)
737
+ if b0.overlaps(b1):
738
+ ref_note.set_position((ref_note.xyann[0], 13.5))
739
+
740
+ return _finish_hist
741
+
742
+ return Panel(
743
+ kind="distribution",
744
+ title=title,
745
+ label=label,
746
+ unit=unit,
747
+ spec=_base_spec(
748
+ title,
749
+ label,
750
+ given_unit,
751
+ groups=_jsonable(given.get("", given)),
752
+ highlight=hl or None,
753
+ baseline=base,
754
+ reference=list(ref) if ref else None,
755
+ log=log or None,
756
+ stat=stat if stat != "median" else None,
757
+ bins=bins_spec,
758
+ fmt=fmt,
759
+ ),
760
+ facts=facts,
761
+ alt_facts=alt_facts,
762
+ describe=(
763
+ f"Histogram of {label or 'values'}"
764
+ + (f" ({unit})" if unit else "")
765
+ + f" across {bin_note} (n={data[nm0].size})"
766
+ ),
767
+ _height_mm=lambda w, _m, _s, _t: min(54.0, max(36.0, 0.40 * w)) + 4.0,
768
+ _min_height_mm=lambda _w, _m, _s, _t: 32.0,
769
+ stretch=True,
770
+ _draw=_draw_single_hist,
771
+ measure_note=single_measure,
772
+ color_items=tuple(nm for nm in names if nm),
773
+ color_focus=tuple(hl),
774
+ color_mode="highlight" if hl else "uniform",
775
+ uses_default=not hl,
776
+ color_baseline=base,
777
+ )
778
+
779
+ def _hist_frames(ctx: _Ctx, ax: Axes, rect: Bbox) -> list[tuple[Axes, Bbox]]:
780
+ sz = ctx.sizes
781
+ theme = ctx.theme
782
+ accent = {
783
+ name: col for name, col in ctx.colors.items() if name in names and name != base
784
+ }
785
+ ax.remove()
786
+ nrows = len(names)
787
+ px_per_mm = float(ctx.fig.dpi) / 25.4
788
+ gap_y = 4.0 * px_per_mm * sz.scale
789
+ cell_h = (rect.height - gap_y * (nrows - 1)) / nrows
790
+ frames: list[tuple[Axes, Bbox]] = []
791
+ top_ref_note: Any = None
792
+ top_child: Axes | None = None
793
+ for idx, nm in enumerate(names):
794
+ y1 = rect.y1 - idx * (cell_h + gap_y)
795
+ sub = Bbox.from_extents(rect.x0, y1 - cell_h, rect.x1, y1)
796
+ child = ctx.fig.add_axes([0.1, 0.1, 0.5, 0.5])
797
+ ctx.tag(child)
798
+ ctx.extra_axes.append(child)
799
+ _setup_hist_axes(
800
+ child,
801
+ sz,
802
+ theme,
803
+ show_x=(idx == nrows - 1),
804
+ nbins_y=3,
805
+ cell_w_mm=ctx.cell_width_mm,
806
+ )
807
+ _draw_hist_bars(ctx, child, nm, accent, sz, theme)
808
+ col = (
809
+ ctx.colors.get(nm, theme.ink)
810
+ if nm == base
811
+ else accent.get(nm, theme.ink if not (hl or accent) else theme.muted)
812
+ )
813
+ med = stats[nm][1]
814
+ title_col = ctx.text_color(col) if nm in accent else theme.ink
815
+ child.set_title(
816
+ _plain(f"{nm} ({stat} {_with_unit(fmt_fn(med), unit)}, n={data[nm].size})", theme),
817
+ loc="left",
818
+ fontsize=sz.small,
819
+ fontweight="bold" if (nm in accent or nm == base) else "normal",
820
+ color=title_col,
821
+ pad=3.0,
822
+ )
823
+ if idx == 0 and ref is not None and ref[1]:
824
+ top_child = child
825
+ top_ref_note = child.annotate(
826
+ _plain(ref[1], theme),
827
+ (ref[0], 1.0),
828
+ xycoords=("data", "axes fraction"),
829
+ xytext=(3.0, 2.5),
830
+ textcoords="offset points",
831
+ ha="left",
832
+ va="bottom",
833
+ fontsize=sz.small,
834
+ color=theme.muted,
835
+ annotation_clip=False,
836
+ )
837
+ frames.append((child, sub))
838
+
839
+ def _equalize_hist() -> None:
840
+ fig_w = ctx.fig.bbox.width
841
+ left = max(child.get_position().x0 * fig_w for child, _ in frames)
842
+ right = min(child.get_position().x1 * fig_w for child, _ in frames)
843
+ for child, _ in frames:
844
+ pos = child.get_position()
845
+ child.set_position([left / fig_w, pos.y0, max(1.0, right - left) / fig_w, pos.height])
846
+ if top_ref_note is not None and top_child is not None:
847
+ _keep_inside_x(ctx, top_child, top_ref_note)
848
+ renderer = ctx.fig.canvas.get_renderer()
849
+ t_title = getattr(top_child, "_left_title", None)
850
+ if t_title is not None and t_title.get_window_extent(renderer).overlaps(
851
+ top_ref_note.get_window_extent(renderer)
852
+ ):
853
+ top_ref_note.set_position((3.0, -10.0))
854
+ top_ref_note.set_va("top")
855
+
856
+ ctx.finishers.append(_equalize_hist)
857
+ return frames
858
+
859
+ return Panel(
860
+ kind="distribution",
861
+ title=title,
862
+ label=label,
863
+ unit=unit,
864
+ spec=_base_spec(
865
+ title,
866
+ label,
867
+ given_unit,
868
+ groups=_jsonable(given),
869
+ highlight=hl or None,
870
+ baseline=base,
871
+ reference=list(ref) if ref else None,
872
+ log=log or None,
873
+ stat=stat if stat != "median" else None,
874
+ bins=bins_spec,
875
+ fmt=fmt,
876
+ ),
877
+ facts=facts,
878
+ alt_facts=alt_facts,
879
+ describe=(
880
+ f"Stacked histograms of {label or 'values'}"
881
+ + (f" ({unit})" if unit else "")
882
+ + f" for {len(names)} groups across {bin_note}"
883
+ ),
884
+ _height_mm=lambda _w, _m, _s, _t: 22.0 * len(names) + 14.0,
885
+ _min_height_mm=lambda _w, _m, _s, _t: 18.0 * len(names) + 12.0,
886
+ _draw=lambda _ctx, _ax: None,
887
+ _frames=_hist_frames,
888
+ measure_note=single_measure,
889
+ color_items=tuple(nm for nm in names if nm),
890
+ color_focus=tuple(hl),
891
+ color_mode="highlight" if hl else "uniform",
892
+ uses_default=not hl,
893
+ color_baseline=base,
894
+ )
895
+
896
+ def _draw(ctx: _Ctx, ax: Axes) -> Callable[[], None] | None:
897
+ sz = ctx.sizes
898
+ theme = ctx.theme
899
+ accent = {
900
+ name: col for name, col in ctx.colors.items() if name in names and name != base
901
+ }
902
+ n = len(names)
903
+ if log:
904
+ ax.set_xscale("log")
905
+ _value_axis(ax, sz, theme, axis="x", nbins=5 if ctx.cell_width_mm >= 100 else 3)
906
+ ax.spines["left"].set_visible(False)
907
+ ax.spines["bottom"].set_visible(False)
908
+ if theme.grid_style != "none" and theme.grid_lw > 0:
909
+ ax.grid(
910
+ axis="x",
911
+ color=theme.grid,
912
+ linestyle=theme.grid_style,
913
+ linewidth=theme.grid_lw,
914
+ )
915
+ ax.grid(axis="y", visible=False)
916
+ ax.set_ylim((n - 0.35, -0.65) if mode == "quantile" else (n - 0.45, -0.6))
917
+ lo, hi = float(everything.min()), float(everything.max())
918
+ if ref is not None:
919
+ lo, hi = min(lo, ref[0]), max(hi, ref[0])
920
+ if log:
921
+ ax.set_xlim(
922
+ *_narrow_log_ticks(
923
+ ax.xaxis, lo / 1.12, hi * 1.12, theme.minus_sign, extend=False, data_hi=hi
924
+ )
925
+ )
926
+ else:
927
+ span = (hi - lo) or abs(hi) or 1.0
928
+ ax.set_xlim(lo - 0.04 * span, hi + 0.04 * span)
929
+ # The value axis covers every dot (re-checked after tick thinning).
930
+ ax._mintfig_cover = (lo, hi) # type: ignore[attr-defined]
931
+ # After layout: >= 3 round ticks bracketing every dot (_bracket_with_ticks).
932
+ ax._mintfig_bracket = ( # type: ignore[attr-defined]
933
+ lo,
934
+ hi,
935
+ 6 if ctx.cell_width_mm >= 100 else 4,
936
+ theme.minus_sign,
937
+ )
938
+ _cover_with_ticks(ax.xaxis, lo, hi)
939
+ ax.set_yticks(range(n), [""] * n)
940
+ ax.tick_params(axis="y", length=0)
941
+ ax.annotate(
942
+ stat,
943
+ (1.0, 1.0),
944
+ xycoords="axes fraction",
945
+ xytext=(6.0, 2.5),
946
+ textcoords="offset points",
947
+ ha="left",
948
+ va="bottom",
949
+ fontsize=sz.small,
950
+ color=theme.muted,
951
+ annotation_clip=False,
952
+ )
953
+ rng = np.random.default_rng(0)
954
+ row_colors: dict[str, str] = {}
955
+ for row, name in enumerate(names):
956
+ arr = data[name]
957
+ if name == base:
958
+ col = ctx.colors.get(name, theme.ink)
959
+ else:
960
+ col = accent.get(name, theme.context_line if (hl or accent) else ctx.default_color)
961
+ row_colors[name] = col
962
+ q1, med, q3 = stats[name]
963
+ if log:
964
+ q1 = max(q1, ax.get_xlim()[0])
965
+ if mode == "dots":
966
+ shown = arr if arr.size <= 600 else rng.choice(arr, size=600, replace=False)
967
+ alpha = 0.8 if shown.size <= 30 else (0.5 if shown.size <= 150 else 0.28)
968
+ jitter = rng.uniform(-0.2, 0.2, size=shown.size)
969
+ ax.scatter(
970
+ shown,
971
+ row + jitter,
972
+ s=(3.4 * sz.scale) ** 2,
973
+ color=col,
974
+ alpha=alpha,
975
+ linewidth=0,
976
+ zorder=2,
977
+ )
978
+ # Summary through the dot row: a thin line for the middle half (or +/- 1 s.d.)
979
+ # and a taller tick for the centre, haloed so it reads over the dots. With
980
+ # fewer than five observations quartiles and s.d. mean little: the centre
981
+ # tick only.
982
+ halo = [
983
+ patheffects.withStroke(
984
+ linewidth=2.6 * sz.scale, foreground=theme.background, alpha=0.9
985
+ )
986
+ ]
987
+ if arr.size >= 5:
988
+ ax.hlines(
989
+ row,
990
+ q1,
991
+ q3,
992
+ color=theme.ink,
993
+ linewidth=1.0 * sz.scale,
994
+ zorder=4,
995
+ path_effects=halo,
996
+ )
997
+ ax.vlines(
998
+ med,
999
+ row - 0.3,
1000
+ row + 0.3,
1001
+ color=theme.ink,
1002
+ linewidth=2.0 * sz.scale,
1003
+ zorder=5,
1004
+ path_effects=halo,
1005
+ )
1006
+ for text, dy, va, size, color, weight in (
1007
+ (name, 0.5, "bottom", sz.body, theme.ink, "bold" if name in accent else "normal"),
1008
+ (f"n={arr.size}", -1.5, "top", sz.foot, theme.muted, "normal"),
1009
+ ):
1010
+ ax.annotate(
1011
+ _plain(text, theme),
1012
+ (0.0, row),
1013
+ xycoords=("axes fraction", "data"),
1014
+ xytext=(-7.0, dy),
1015
+ textcoords="offset points",
1016
+ ha="right",
1017
+ va=va,
1018
+ fontsize=size,
1019
+ color=color,
1020
+ fontweight=weight,
1021
+ annotation_clip=False,
1022
+ )
1023
+ value = (
1024
+ _with_unit(fmt_fn(med), unit) if (row == 0 or _inline_unit(unit)) else fmt_fn(med)
1025
+ )
1026
+ ax.annotate(
1027
+ _plain(value, theme),
1028
+ (1.0, row),
1029
+ xycoords=("axes fraction", "data"),
1030
+ xytext=(6.0, 0.0),
1031
+ textcoords="offset points",
1032
+ ha="left",
1033
+ va="center",
1034
+ fontsize=sz.small,
1035
+ color=theme.ink,
1036
+ fontweight="bold" if name in accent else "normal",
1037
+ annotation_clip=False,
1038
+ )
1039
+ ref_note: Any = None
1040
+ if ref is not None:
1041
+ ax.axvline(ref[0], color=theme.ink, linewidth=0.7, linestyle=(0, (3, 2)), zorder=3)
1042
+ if ref[1]:
1043
+ ref_note = ax.annotate(
1044
+ _plain(ref[1], theme),
1045
+ (ref[0], 1.0),
1046
+ xycoords=("data", "axes fraction"),
1047
+ xytext=(0.0, 2.5),
1048
+ textcoords="offset points",
1049
+ ha="center",
1050
+ va="bottom",
1051
+ fontsize=sz.small,
1052
+ color=theme.muted,
1053
+ annotation_clip=False,
1054
+ )
1055
+ if mode == "quantile":
1056
+
1057
+ def _finish_quantile() -> None:
1058
+ if ref_note is not None:
1059
+ _keep_inside_x(ctx, ax, ref_note)
1060
+ renderer = ctx.fig.canvas.get_renderer()
1061
+ frame = ax.get_window_extent(renderer)
1062
+ w_pt = max(30.0, frame.width * ctx.pt_per_px)
1063
+ h_pt = max(20.0, frame.height * ctx.pt_per_px)
1064
+ row_h_pt = h_pt / max(1, n)
1065
+ x0_v, x1_v = sorted(ax.get_xlim())
1066
+ x_lo_s = float(np.log10(max(x0_v, 1e-300))) if log else float(x0_v)
1067
+ x_hi_s = float(np.log10(max(x1_v, 1e-300))) if log else float(x1_v)
1068
+ x_span = (x_hi_s - x_lo_s) or 1.0
1069
+ avail_h_pt = 0.72 * row_h_pt
1070
+ d_pt = (4.8 if q <= 25 else 3.8) * sz.scale
1071
+ binned: dict[str, list[tuple[float, int]]] = {}
1072
+ max_stack = 1
1073
+ for _ in range(10):
1074
+ bw = (1.26 * d_pt / w_pt) * x_span
1075
+ binned = {
1076
+ nm: _wilkinson_stack(
1077
+ np.log10(qvals[nm]) if log else qvals[nm],
1078
+ bw,
1079
+ )
1080
+ for nm in names
1081
+ }
1082
+ max_stack = max(
1083
+ (cnt for stacks in binned.values() for _, cnt in stacks),
1084
+ default=1,
1085
+ )
1086
+ if max_stack * 1.12 * d_pt <= avail_h_pt:
1087
+ break
1088
+ d_pt = max(1.8 * sz.scale, min(d_pt * 0.88, avail_h_pt / (max_stack * 1.12)))
1089
+ dy_data = min((1.12 * d_pt) / max(row_h_pt, 1.0), 0.72 / max(1, max_stack))
1090
+ halo = [
1091
+ patheffects.withStroke(
1092
+ linewidth=2.2 * sz.scale, foreground=theme.background, alpha=0.9
1093
+ )
1094
+ ]
1095
+ for row, name in enumerate(names):
1096
+ col = row_colors[name]
1097
+ y_base = row + 0.32
1098
+ ax.hlines(
1099
+ y_base,
1100
+ float(qvals[name][0]),
1101
+ float(qvals[name][-1]),
1102
+ color=theme.grid,
1103
+ linewidth=0.6 * sz.scale,
1104
+ zorder=1,
1105
+ )
1106
+ dot_xs: list[float] = []
1107
+ dot_ys: list[float] = []
1108
+ for cx_s, count in binned[name]:
1109
+ cx = float(10.0**cx_s) if log else float(cx_s)
1110
+ for k in range(count):
1111
+ dot_xs.append(cx)
1112
+ dot_ys.append(y_base - (k + 0.55) * dy_data)
1113
+ ax.scatter(
1114
+ dot_xs,
1115
+ dot_ys,
1116
+ s=d_pt**2,
1117
+ color=col,
1118
+ edgecolor=theme.background,
1119
+ linewidth=0.45 * sz.scale,
1120
+ alpha=0.92,
1121
+ zorder=3,
1122
+ )
1123
+ q1, med, q3 = stats[name]
1124
+ if log:
1125
+ q1 = max(q1, ax.get_xlim()[0])
1126
+ mark_y = y_base + 0.055
1127
+ if data[name].size >= 5:
1128
+ ax.hlines(
1129
+ mark_y,
1130
+ q1,
1131
+ q3,
1132
+ color=theme.ink,
1133
+ linewidth=1.25 * sz.scale,
1134
+ alpha=0.72,
1135
+ zorder=4,
1136
+ path_effects=halo,
1137
+ )
1138
+ ax.vlines(
1139
+ med,
1140
+ y_base - 0.05,
1141
+ y_base + 0.14,
1142
+ color=theme.ink,
1143
+ linewidth=1.8 * sz.scale,
1144
+ zorder=5,
1145
+ path_effects=halo,
1146
+ )
1147
+
1148
+ return _finish_quantile
1149
+ if ref_note is not None:
1150
+ return lambda: _keep_inside_x(ctx, ax, ref_note)
1151
+ return None
1152
+
1153
+ pct_each = 100.0 / q
1154
+ pct_txt = f"{pct_each:.0f}%" if abs(pct_each - round(pct_each)) < 1e-6 else f"{pct_each:.1f}%"
1155
+ if mode == "quantile":
1156
+ panel_describe = (
1157
+ f"Quantile dotplot ({q} dots/group, {pct_txt} each) of {label or 'values'}"
1158
+ + (f" ({unit})" if unit else "")
1159
+ + f" for {len(names)} group(s), with {stat} centre mark"
1160
+ )
1161
+ panel_measure_note = f"quantile dotplot ({q} dots/group, {pct_txt} each); tick: {stat}"
1162
+ height_fn = lambda _w, _m, _s, _t: max(26.0, 14.5 * len(names) + 12.0)
1163
+ min_height_fn = lambda _w, _m, _s, _t: max(22.0, 11.5 * len(names) + 11.0)
1164
+ else:
1165
+ panel_describe = (
1166
+ f"Dot strips of {label or 'values'}"
1167
+ + (f" ({unit})" if unit else "")
1168
+ + f" for {len(names)} group(s), each with "
1169
+ + (
1170
+ f"a {stat} tick"
1171
+ if not any_spread
1172
+ else "a mean tick and a \N{PLUS-MINUS SIGN} 1 s.d. line"
1173
+ if stat == "mean"
1174
+ else "a median tick and a line over the middle half (interquartile range)"
1175
+ )
1176
+ )
1177
+ # The spread line is drawn only for groups with n >= 5: caption it only then.
1178
+ panel_measure_note = (
1179
+ f"tick: {stat}"
1180
+ if not any_spread
1181
+ else (
1182
+ "tick: mean; line: \N{PLUS-MINUS SIGN} 1 s.d."
1183
+ if stat == "mean"
1184
+ else "tick: median; line: middle half"
1185
+ )
1186
+ + (
1187
+ ""
1188
+ if all(a.size >= 5 for a in data.values())
1189
+ else " (n \N{GREATER-THAN OR EQUAL TO} 5)"
1190
+ )
1191
+ )
1192
+ height_fn = lambda _w, _m, _s, _t: 8.5 * len(names) + 11.0
1193
+ min_height_fn = lambda _w, _m, _s, _t: 6.5 * len(names) + 11.0
1194
+
1195
+ return Panel(
1196
+ kind="distribution",
1197
+ title=title,
1198
+ label=label,
1199
+ unit=unit,
1200
+ spec=_base_spec(
1201
+ title,
1202
+ label,
1203
+ given_unit,
1204
+ groups=_jsonable(given.get("", given)),
1205
+ highlight=hl or None,
1206
+ baseline=base,
1207
+ reference=list(ref) if ref else None,
1208
+ log=log or None,
1209
+ stat=stat if stat != "median" else None,
1210
+ fmt=fmt,
1211
+ mode=mode if mode != "dots" else None,
1212
+ quantiles=q if mode == "quantile" else None,
1213
+ ),
1214
+ facts=facts,
1215
+ alt_facts=alt_facts,
1216
+ describe=panel_describe,
1217
+ _height_mm=height_fn,
1218
+ _min_height_mm=min_height_fn,
1219
+ _draw=_draw,
1220
+ measure_note=panel_measure_note,
1221
+ color_items=tuple(nm for nm in names if nm),
1222
+ color_focus=tuple(hl),
1223
+ color_mode="highlight" if hl else "uniform",
1224
+ uses_default=not hl,
1225
+ color_baseline=base,
1226
+ )
1227
+
1228
+
1229
+ @_guarded("histogram")
1230
+ def histogram(
1231
+ values: Mapping[str, Sequence[float]] | Sequence[float] | Sequence[Mapping[str, Any]],
1232
+ *,
1233
+ group: str | None = None,
1234
+ value: str | None = None,
1235
+ bins: int | str | Sequence[float] = "auto",
1236
+ title: str | None = None,
1237
+ label: str | None = None,
1238
+ unit: str | None = None,
1239
+ highlight: str | Sequence[str] | None = None,
1240
+ baseline: str | None = None,
1241
+ reference: float | tuple[float, str] | None = None,
1242
+ log: bool = False,
1243
+ stat: str = "median",
1244
+ fmt: str | None = None,
1245
+ ) -> Panel:
1246
+ """How is a continuous variable shaped? Alias for ``distribution(..., bins=bins)``.
1247
+
1248
+ Pass a single list/array of observations for a histogram, a dict of up to
1249
+ 4 named groups for stacked shared-axis histograms, or row-shaped data /
1250
+ DataFrame with ``value=`` (and optional ``group=``). ``bins`` accepts
1251
+ ``"auto"`` (default), a bin count (2–60), a numpy binning rule, or explicit
1252
+ bin edges.
1253
+ """
1254
+ return distribution(
1255
+ values,
1256
+ group=group,
1257
+ value=value,
1258
+ bins=bins,
1259
+ title=title,
1260
+ label=label,
1261
+ unit=unit,
1262
+ highlight=highlight,
1263
+ baseline=baseline,
1264
+ reference=reference,
1265
+ log=log,
1266
+ stat=stat,
1267
+ fmt=fmt,
1268
+ )