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.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1308 @@
|
|
|
1
|
+
"""compare() and share() forms for mint.explain."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from matplotlib.axes import Axes
|
|
11
|
+
from matplotlib.ticker import (
|
|
12
|
+
FuncFormatter,
|
|
13
|
+
MaxNLocator,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from ..themes import (
|
|
17
|
+
MINTFIG_THEME,
|
|
18
|
+
Theme,
|
|
19
|
+
contrast_ratio,
|
|
20
|
+
)
|
|
21
|
+
from .core import (
|
|
22
|
+
COMFORTABLE_COMPARE_ITEMS,
|
|
23
|
+
MAX_COMPARE_ITEMS,
|
|
24
|
+
PT_TO_MM,
|
|
25
|
+
ExplainError,
|
|
26
|
+
Panel,
|
|
27
|
+
_and_list,
|
|
28
|
+
_bare_axes,
|
|
29
|
+
_base_spec,
|
|
30
|
+
_baseline_name,
|
|
31
|
+
_cover_with_ticks,
|
|
32
|
+
_Ctx,
|
|
33
|
+
_diff_with_unit,
|
|
34
|
+
_formatter,
|
|
35
|
+
_guarded,
|
|
36
|
+
_halfwidth,
|
|
37
|
+
_has_items,
|
|
38
|
+
_inline_unit,
|
|
39
|
+
_interval_issue,
|
|
40
|
+
_interval_mode_text,
|
|
41
|
+
_is_number,
|
|
42
|
+
_is_strict,
|
|
43
|
+
_issue,
|
|
44
|
+
_jsonable,
|
|
45
|
+
_Measure,
|
|
46
|
+
_named_values,
|
|
47
|
+
_names,
|
|
48
|
+
_narrow_log_ticks,
|
|
49
|
+
_or_list,
|
|
50
|
+
_pairs,
|
|
51
|
+
_plain,
|
|
52
|
+
_range_with_unit,
|
|
53
|
+
_ratio_text,
|
|
54
|
+
_record_adjustment,
|
|
55
|
+
_reference_line,
|
|
56
|
+
_shows_zero,
|
|
57
|
+
_sig_text,
|
|
58
|
+
_signed,
|
|
59
|
+
_Sizes,
|
|
60
|
+
_tick_label,
|
|
61
|
+
_to_float,
|
|
62
|
+
_unsigned,
|
|
63
|
+
_vs_text,
|
|
64
|
+
_with_unit,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# --------------------------------------------------------------------------- #
|
|
68
|
+
# compare / share
|
|
69
|
+
# --------------------------------------------------------------------------- #
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _bar_panel(
|
|
73
|
+
*,
|
|
74
|
+
kind: str,
|
|
75
|
+
names: list[str],
|
|
76
|
+
values: list[float],
|
|
77
|
+
highlight: list[str],
|
|
78
|
+
labels: list[str],
|
|
79
|
+
title: str | None,
|
|
80
|
+
label: str | None,
|
|
81
|
+
unit: str | None,
|
|
82
|
+
spec: dict[str, Any],
|
|
83
|
+
facts: list[str],
|
|
84
|
+
describe: str,
|
|
85
|
+
dots: bool,
|
|
86
|
+
errors: dict[str, tuple[float, float]] | None,
|
|
87
|
+
reference: tuple[float, str] | None,
|
|
88
|
+
muted_names: Sequence[str] = (),
|
|
89
|
+
issues: list[dict[str, Any]] | None = None,
|
|
90
|
+
log: bool = False,
|
|
91
|
+
measure_note: str | None = None,
|
|
92
|
+
baseline: str | None = None,
|
|
93
|
+
counts: Mapping[str, int] | None = None,
|
|
94
|
+
boosts: Sequence[float] | None = None,
|
|
95
|
+
inner_errors: dict[str, tuple[float, float]] | None = None,
|
|
96
|
+
) -> Panel:
|
|
97
|
+
n = len(names)
|
|
98
|
+
hl_index = {name: i for i, name in enumerate(highlight)}
|
|
99
|
+
counts = dict(counts or {})
|
|
100
|
+
|
|
101
|
+
def _wrapped(
|
|
102
|
+
cell_width_mm: float,
|
|
103
|
+
measure: _Measure,
|
|
104
|
+
sizes: _Sizes,
|
|
105
|
+
theme: Theme = MINTFIG_THEME,
|
|
106
|
+
) -> list[str]:
|
|
107
|
+
"""Item names wrapped to two lines so long names never squeeze the bars."""
|
|
108
|
+
cell_pt = cell_width_mm * sizes.scale / PT_TO_MM
|
|
109
|
+
ell = theme.ellipsis
|
|
110
|
+
out: list[str] = []
|
|
111
|
+
for name in names:
|
|
112
|
+
weight = "bold" if name in hl_index else "normal"
|
|
113
|
+
lines = measure.wrap(name, 0.42 * cell_pt, sizes.body, weight)
|
|
114
|
+
if len(lines) > 3: # a long name wraps onto up to three lines before any is cut
|
|
115
|
+
lines = [*lines[:2], " ".join(lines[2:])]
|
|
116
|
+
fitted: list[str] = []
|
|
117
|
+
for line in lines:
|
|
118
|
+
min_len = max(4, len(ell) + 2)
|
|
119
|
+
while (
|
|
120
|
+
len(line) > min_len
|
|
121
|
+
and measure.width_pt(line, sizes.body, weight) > 0.5 * cell_pt
|
|
122
|
+
):
|
|
123
|
+
if len(ell) == 1:
|
|
124
|
+
line = line[:-2].rstrip() + ell
|
|
125
|
+
else:
|
|
126
|
+
base = line.removesuffix(ell)
|
|
127
|
+
line = base[:-1].rstrip() + ell
|
|
128
|
+
fitted.append(line)
|
|
129
|
+
out.append("\n".join(fitted))
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
def _truncated(shown: list[str], theme: Theme = MINTFIG_THEME) -> list[str]:
|
|
133
|
+
"""Names cut on any of their lines (a long first word is cut too, not only the last)."""
|
|
134
|
+
ell = theme.ellipsis
|
|
135
|
+
return [
|
|
136
|
+
name
|
|
137
|
+
for name, text in zip(names, shown, strict=True)
|
|
138
|
+
if text.replace("\n", " ").count(ell) > name.count(ell)
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
def _pitch(wrapped: list[str], tight: bool = False) -> float:
|
|
142
|
+
lines = max(name.count("\n") + 1 for name in wrapped)
|
|
143
|
+
# A count under each name ("n=84") takes about one small line more.
|
|
144
|
+
extra = (2.4 if tight else 2.8) if counts else 0.0
|
|
145
|
+
if tight: # the closest pitch at which names and value labels still clear
|
|
146
|
+
return {1: 4.6, 2: 7.2}.get(lines, 10.0) + extra
|
|
147
|
+
return {1: 5.3, 2: 8.2}.get(lines, 11.0) + extra
|
|
148
|
+
|
|
149
|
+
def _extras() -> float:
|
|
150
|
+
return (4.0 if reference and reference[1] else 0.0) + (5.0 if (log or errors) else 0.0)
|
|
151
|
+
|
|
152
|
+
def _draw(ctx: _Ctx, ax: Axes) -> Callable[[], None] | None:
|
|
153
|
+
sz = ctx.sizes
|
|
154
|
+
theme = ctx.theme
|
|
155
|
+
# Figure-level colours: highlighted names, or (without highlight) names that are
|
|
156
|
+
# coloured elsewhere in the figure; every other item is context grey.
|
|
157
|
+
# The baseline is drawn in ink (or its pinned colour) at normal weight: a
|
|
158
|
+
# reference, not an emphasis, so it never turns the other items grey.
|
|
159
|
+
accent = {
|
|
160
|
+
name: col for name, col in ctx.colors.items() if name in names and name != baseline
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
def _color(name: str) -> str:
|
|
164
|
+
if name == baseline:
|
|
165
|
+
return ctx.colors.get(name, theme.ink)
|
|
166
|
+
if highlight or accent:
|
|
167
|
+
return accent.get(name, theme.context_fill)
|
|
168
|
+
return theme.context_fill if name in muted_names else ctx.default_color
|
|
169
|
+
|
|
170
|
+
y = np.arange(n, dtype=float)
|
|
171
|
+
vals = np.asarray(values, dtype=float)
|
|
172
|
+
boost_arr = np.asarray(boosts, dtype=float) if boosts is not None else None
|
|
173
|
+
totals = vals + boost_arr if boost_arr is not None else vals
|
|
174
|
+
colors = [_color(name) for name in names]
|
|
175
|
+
lows = np.array([errors[nm][0] if errors else v for nm, v in zip(names, vals, strict=True)])
|
|
176
|
+
highs = np.array(
|
|
177
|
+
[errors[nm][1] if errors else v for nm, v in zip(names, totals, strict=True)]
|
|
178
|
+
)
|
|
179
|
+
_bare_axes(ax)
|
|
180
|
+
ax.set_ylim(n - 0.5, -0.5)
|
|
181
|
+
|
|
182
|
+
if dots:
|
|
183
|
+
lo = float(min(lows.min(), reference[0] if reference else np.inf))
|
|
184
|
+
hi = float(max(highs.max(), reference[0] if reference else -np.inf))
|
|
185
|
+
if log:
|
|
186
|
+
ax.set_xscale("log")
|
|
187
|
+
pad = max((hi / lo) ** 0.05, 1.15)
|
|
188
|
+
ax.set_xlim(
|
|
189
|
+
*_narrow_log_ticks(
|
|
190
|
+
ax.xaxis, lo / pad, hi * pad, theme.minus_sign, extend=False, data_hi=hi
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
else:
|
|
194
|
+
if not errors and lo >= 0 and (hi - lo) > 0.6 * hi:
|
|
195
|
+
lo = 0.0 # the spread already covers most of the way to zero
|
|
196
|
+
span = (hi - lo) or abs(hi) or 1.0
|
|
197
|
+
ax.set_xlim(lo - 0.05 * span, hi + 0.03 * span)
|
|
198
|
+
left = ax.get_xlim()[0]
|
|
199
|
+
stem_color = theme.grid if theme.grid_style != "none" else theme.context_fill
|
|
200
|
+
dot_colors = [c if c != theme.context_fill else theme.axis for c in colors]
|
|
201
|
+
if errors:
|
|
202
|
+
# Thin whiskers with small end caps: the caps stay visible beside the dot,
|
|
203
|
+
# and the value axis below lets the reader measure each interval.
|
|
204
|
+
ax.hlines(y, lows, highs, color=dot_colors, linewidth=0.9 * sz.scale, zorder=2)
|
|
205
|
+
for ends in (lows, highs):
|
|
206
|
+
ax.vlines(
|
|
207
|
+
ends,
|
|
208
|
+
y - 0.16,
|
|
209
|
+
y + 0.16,
|
|
210
|
+
color=dot_colors,
|
|
211
|
+
linewidth=0.9 * sz.scale,
|
|
212
|
+
zorder=2,
|
|
213
|
+
)
|
|
214
|
+
if inner_errors is not None:
|
|
215
|
+
in_lows = np.array([inner_errors[nm][0] for nm in names], dtype=float)
|
|
216
|
+
in_highs = np.array([inner_errors[nm][1] for nm in names], dtype=float)
|
|
217
|
+
ax.hlines(
|
|
218
|
+
y,
|
|
219
|
+
in_lows,
|
|
220
|
+
in_highs,
|
|
221
|
+
color=dot_colors,
|
|
222
|
+
linewidth=2.6 * sz.scale,
|
|
223
|
+
capstyle="round",
|
|
224
|
+
zorder=2.5,
|
|
225
|
+
)
|
|
226
|
+
else:
|
|
227
|
+
ax.hlines(y, left, vals, color=stem_color, linewidth=0.7, zorder=1)
|
|
228
|
+
ax.scatter(
|
|
229
|
+
vals,
|
|
230
|
+
y,
|
|
231
|
+
s=(5.2 * sz.scale) ** 2,
|
|
232
|
+
color=dot_colors,
|
|
233
|
+
edgecolor=theme.background,
|
|
234
|
+
linewidth=0.6,
|
|
235
|
+
zorder=3,
|
|
236
|
+
)
|
|
237
|
+
else:
|
|
238
|
+
lo = float(min(0.0, vals.min(), reference[0] if reference else 0.0))
|
|
239
|
+
hi = float(max(0.0, totals.max(), reference[0] if reference else 0.0))
|
|
240
|
+
if hi == lo:
|
|
241
|
+
hi = lo + 1.0
|
|
242
|
+
ax.set_xlim(lo, hi)
|
|
243
|
+
bar_kw: dict[str, Any] = {
|
|
244
|
+
"height": theme.bar_height,
|
|
245
|
+
"color": colors,
|
|
246
|
+
"linewidth": theme.bar_edge_lw,
|
|
247
|
+
"zorder": 2,
|
|
248
|
+
}
|
|
249
|
+
if theme.bar_edgecolor is not None and theme.bar_edge_lw > 0:
|
|
250
|
+
bar_kw["edgecolor"] = theme.bar_edgecolor
|
|
251
|
+
ax.barh(y, vals, **bar_kw)
|
|
252
|
+
if boost_arr is not None:
|
|
253
|
+
for yi, b_val, b_ext, col in zip(y, vals, boost_arr, colors, strict=True):
|
|
254
|
+
if b_ext <= 0:
|
|
255
|
+
continue
|
|
256
|
+
ax.barh(
|
|
257
|
+
[yi],
|
|
258
|
+
[b_ext],
|
|
259
|
+
left=[b_val],
|
|
260
|
+
height=theme.bar_height,
|
|
261
|
+
color=col,
|
|
262
|
+
alpha=0.34,
|
|
263
|
+
edgecolor=col,
|
|
264
|
+
linewidth=0.9 * sz.scale,
|
|
265
|
+
zorder=2,
|
|
266
|
+
)
|
|
267
|
+
ax.axvline(0.0, color=theme.zero_line, linewidth=theme.zero_line_lw, zorder=3)
|
|
268
|
+
|
|
269
|
+
if log:
|
|
270
|
+
# A log scale must be visible: the reader cannot infer it from the dots.
|
|
271
|
+
ax.tick_params(
|
|
272
|
+
axis="x",
|
|
273
|
+
length=theme.tick_length,
|
|
274
|
+
width=theme.tick_width,
|
|
275
|
+
color=theme.axis,
|
|
276
|
+
labelsize=sz.small,
|
|
277
|
+
labelcolor=theme.muted,
|
|
278
|
+
)
|
|
279
|
+
ax.spines["bottom"].set_visible(True)
|
|
280
|
+
ax.spines["bottom"].set_color(theme.axis)
|
|
281
|
+
ax.spines["bottom"].set_linewidth(theme.axis_lw)
|
|
282
|
+
elif errors:
|
|
283
|
+
# Intervals need a scale to be read: a light value axis like trend's.
|
|
284
|
+
minus = theme.minus_sign
|
|
285
|
+
ax.xaxis.set_major_locator(MaxNLocator(nbins=4, steps=[1, 2, 2.5, 5, 10]))
|
|
286
|
+
ax.xaxis.set_major_formatter(
|
|
287
|
+
FuncFormatter(lambda v, _p, m=minus, a=ax.xaxis: _tick_label(v, m, a))
|
|
288
|
+
)
|
|
289
|
+
ax.tick_params(axis="x", length=0, labelsize=sz.small, labelcolor=theme.muted, pad=3)
|
|
290
|
+
if theme.grid_style != "none" and theme.grid_lw > 0:
|
|
291
|
+
ax.grid(
|
|
292
|
+
axis="x", color=theme.grid, linestyle=theme.grid_style, linewidth=theme.grid_lw
|
|
293
|
+
)
|
|
294
|
+
ax.set_axisbelow(True)
|
|
295
|
+
cover = (float(lows.min()), float(highs.max()))
|
|
296
|
+
if reference is not None:
|
|
297
|
+
cover = (min(cover[0], reference[0]), max(cover[1], reference[0]))
|
|
298
|
+
ax._mintfig_cover = cover # type: ignore[attr-defined]
|
|
299
|
+
_cover_with_ticks(ax.xaxis, *cover)
|
|
300
|
+
else:
|
|
301
|
+
ax.xaxis.set_visible(False)
|
|
302
|
+
shown_names = _wrapped(ctx.cell_width_mm, ctx.measure, sz, theme)
|
|
303
|
+
cut = _truncated(shown_names, theme)
|
|
304
|
+
if cut:
|
|
305
|
+
ctx.issues.append(
|
|
306
|
+
_issue(
|
|
307
|
+
"names_truncated",
|
|
308
|
+
"warning",
|
|
309
|
+
f"{len(cut)} item name(s) were cut to fit: {', '.join(map(repr, cut[:3]))}.",
|
|
310
|
+
"Shorten the names, or give this panel a full-width row with "
|
|
311
|
+
'layout=[["a"], ["b"]].',
|
|
312
|
+
panel=ctx.key,
|
|
313
|
+
)
|
|
314
|
+
)
|
|
315
|
+
ax.set_yticks(y, [_plain(nm, theme) for nm in shown_names])
|
|
316
|
+
ax.tick_params(axis="y", length=0, labelsize=sz.body, labelcolor=theme.ink, pad=5)
|
|
317
|
+
for tick, name in zip(ax.get_yticklabels(), names, strict=True):
|
|
318
|
+
tick.set_linespacing(1.05)
|
|
319
|
+
if name in accent:
|
|
320
|
+
tick.set_fontweight("bold")
|
|
321
|
+
elif name in muted_names:
|
|
322
|
+
tick.set_color(theme.muted)
|
|
323
|
+
if counts:
|
|
324
|
+
# The name sits just above the mark's centre line, its count just below,
|
|
325
|
+
# as distribution() writes "n=8" under each group name.
|
|
326
|
+
tick.set_verticalalignment("bottom")
|
|
327
|
+
for yi, name in zip(y, names, strict=True):
|
|
328
|
+
if name not in counts:
|
|
329
|
+
continue
|
|
330
|
+
ax.annotate(
|
|
331
|
+
_plain(f"n={counts[name]}", theme),
|
|
332
|
+
(0.0, yi),
|
|
333
|
+
xycoords=("axes fraction", "data"),
|
|
334
|
+
xytext=(-5.0, -1.0),
|
|
335
|
+
textcoords="offset points",
|
|
336
|
+
ha="right",
|
|
337
|
+
va="top",
|
|
338
|
+
fontsize=sz.foot,
|
|
339
|
+
color=theme.muted,
|
|
340
|
+
annotation_clip=False,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
value_notes: list[tuple[Any, float, float, str]] = []
|
|
344
|
+
for yi, name, value, hi_v, lo_v, text, col in zip(
|
|
345
|
+
y, names, vals, highs, lows, labels, colors, strict=True
|
|
346
|
+
):
|
|
347
|
+
anchor = hi_v if (dots or value >= 0) else 0.0
|
|
348
|
+
value_note = ax.annotate(
|
|
349
|
+
_plain(text, theme),
|
|
350
|
+
(anchor, yi),
|
|
351
|
+
xytext=(5.0 if (dots or value >= 0) else 4.0, 0.0),
|
|
352
|
+
textcoords="offset points",
|
|
353
|
+
ha="left",
|
|
354
|
+
va="center",
|
|
355
|
+
fontsize=sz.small,
|
|
356
|
+
color=theme.muted if name in muted_names else theme.ink,
|
|
357
|
+
fontweight="bold" if name in accent else "normal",
|
|
358
|
+
annotation_clip=False,
|
|
359
|
+
)
|
|
360
|
+
# Where the value can go instead: left of the mark (dots, from the low end of
|
|
361
|
+
# an interval) or inside the bar's end (bars).
|
|
362
|
+
value_notes.append((value_note, float(lo_v if dots else value), float(value), col))
|
|
363
|
+
|
|
364
|
+
if reference is not None:
|
|
365
|
+
ref_value, ref_text = reference
|
|
366
|
+
ax.axvline(
|
|
367
|
+
ref_value,
|
|
368
|
+
color=theme.ink,
|
|
369
|
+
linewidth=0.7,
|
|
370
|
+
linestyle=(0, (3, 2)),
|
|
371
|
+
zorder=4,
|
|
372
|
+
)
|
|
373
|
+
if ref_text:
|
|
374
|
+
ax.annotate(
|
|
375
|
+
_plain(ref_text, theme),
|
|
376
|
+
(ref_value, 1.0),
|
|
377
|
+
xycoords=("data", "axes fraction"),
|
|
378
|
+
xytext=(0.0, 2.5),
|
|
379
|
+
textcoords="offset points",
|
|
380
|
+
ha="center",
|
|
381
|
+
va="bottom",
|
|
382
|
+
fontsize=sz.small,
|
|
383
|
+
color=theme.muted,
|
|
384
|
+
annotation_clip=False,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
if reference is None:
|
|
388
|
+
return None
|
|
389
|
+
ref_x = reference[0]
|
|
390
|
+
|
|
391
|
+
def _clear_reference() -> None:
|
|
392
|
+
"""A value label the reference line runs through moves past the line, or to the
|
|
393
|
+
other side of its mark when there is no room past it."""
|
|
394
|
+
renderer = ctx.fig.canvas.get_renderer()
|
|
395
|
+
k = ctx.pt_per_px
|
|
396
|
+
cell = ax.get_tightbbox(renderer)
|
|
397
|
+
frame = ax.get_window_extent(renderer)
|
|
398
|
+
right_limit = max(frame.x1, cell.x1 if cell is not None else frame.x1)
|
|
399
|
+
line_px = float(ax.transData.transform((ref_x, 0.0))[0])
|
|
400
|
+
gap = 3.0 / k
|
|
401
|
+
for note, other_anchor, value, col in value_notes:
|
|
402
|
+
box = note.get_window_extent(renderer)
|
|
403
|
+
if not (box.x0 - 1 <= line_px <= box.x1 + 1):
|
|
404
|
+
continue
|
|
405
|
+
dx, dy = note.xyann
|
|
406
|
+
shift = (line_px + gap - box.x0) * k
|
|
407
|
+
note.set_position((dx + shift, dy))
|
|
408
|
+
moved = note.get_window_extent(renderer)
|
|
409
|
+
if moved.x1 <= right_limit + 1:
|
|
410
|
+
continue
|
|
411
|
+
note.xy = (other_anchor, note.xy[1])
|
|
412
|
+
note.set_horizontalalignment("right")
|
|
413
|
+
if dots:
|
|
414
|
+
note.set_position((-5.0, dy))
|
|
415
|
+
else: # inside the bar's end, in whichever of ink or paper reads on it
|
|
416
|
+
note.set_position((-3.0, dy))
|
|
417
|
+
paper = theme.background
|
|
418
|
+
note.set_color(
|
|
419
|
+
paper if contrast_ratio(paper, col) >= contrast_ratio(theme.ink, col)
|
|
420
|
+
else theme.ink
|
|
421
|
+
)
|
|
422
|
+
# Printed on its own bar with a contrasting colour, as a matrix cell's
|
|
423
|
+
# value is: not text lost on data.
|
|
424
|
+
note._mintfig_heatmap_text = True # type: ignore[attr-defined]
|
|
425
|
+
flipped = note.get_window_extent(renderer)
|
|
426
|
+
if flipped.x0 - 1 <= line_px <= flipped.x1 + 1 or flipped.x0 < frame.x0 - 1:
|
|
427
|
+
ctx.issues.append(
|
|
428
|
+
_issue(
|
|
429
|
+
"value_label_on_reference",
|
|
430
|
+
"warning",
|
|
431
|
+
f"The reference line runs through the value label "
|
|
432
|
+
f"{note.get_text()!r} on either side of its mark.",
|
|
433
|
+
"Move the reference to note= (\"dashed line: ...\"), or widen the "
|
|
434
|
+
'panel with a full-width row, layout=[["a"], ["b"]].',
|
|
435
|
+
panel=ctx.key,
|
|
436
|
+
)
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
return _clear_reference
|
|
440
|
+
|
|
441
|
+
return Panel(
|
|
442
|
+
kind=kind,
|
|
443
|
+
title=title,
|
|
444
|
+
label=label,
|
|
445
|
+
unit=unit,
|
|
446
|
+
spec=spec,
|
|
447
|
+
facts=facts,
|
|
448
|
+
describe=describe,
|
|
449
|
+
issues=list(issues or []),
|
|
450
|
+
_height_mm=lambda w, measure, sizes, theme: (
|
|
451
|
+
max(14.0, _pitch(_wrapped(w, measure, sizes, theme)) * n + 1.0) + _extras()
|
|
452
|
+
),
|
|
453
|
+
_min_height_mm=lambda w, measure, sizes, theme: (
|
|
454
|
+
max(12.0, _pitch(_wrapped(w, measure, sizes, theme), tight=True) * n + 1.0) + _extras()
|
|
455
|
+
),
|
|
456
|
+
_draw=_draw,
|
|
457
|
+
measure_note=measure_note,
|
|
458
|
+
color_items=tuple(nm for nm in names if nm not in muted_names),
|
|
459
|
+
color_focus=tuple(highlight),
|
|
460
|
+
color_mode="highlight" if highlight else "uniform",
|
|
461
|
+
uses_default=not highlight,
|
|
462
|
+
color_baseline=baseline,
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _sort_order(sort: object) -> str:
|
|
467
|
+
"""``True``/"desc" -> "desc", "asc" -> "asc", ``False``/None -> "given"."""
|
|
468
|
+
if sort is True or (isinstance(sort, str) and sort.lower() in {"desc", "descending"}):
|
|
469
|
+
return "desc"
|
|
470
|
+
if isinstance(sort, str) and sort.lower() in {"asc", "ascending"}:
|
|
471
|
+
return "asc"
|
|
472
|
+
if sort is False or sort is None or (isinstance(sort, str) and sort.lower() == "none"):
|
|
473
|
+
return "given"
|
|
474
|
+
raise ExplainError(
|
|
475
|
+
f"compare(sort={sort!r}) is not a sort order.",
|
|
476
|
+
fix_hint='Use sort=True or "desc" (largest first), "asc" (smallest first, for '
|
|
477
|
+
"lower-is-better measures such as loss or IC50), or False (keep the order given).",
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _compare_intervals(
|
|
482
|
+
error: object, data: dict[str, float], *, arg: str = "error"
|
|
483
|
+
) -> tuple[dict[str, tuple[float, float]], set[str]]:
|
|
484
|
+
"""Read ``compare(error=...)`` / ``inner_error=``: per item (low, high) or half-width, or one number."""
|
|
485
|
+
names = list(data)
|
|
486
|
+
hint = (
|
|
487
|
+
"Give each item either (low, high) absolute bounds or one number meaning \N{PLUS-MINUS SIGN} "
|
|
488
|
+
f'that much, e.g. {arg}={{"a": (2.8, 3.2), "b": 0.3}}, or {arg}=0.2 for every item.'
|
|
489
|
+
)
|
|
490
|
+
if _is_number(error):
|
|
491
|
+
hw = _halfwidth(error, f"compare({arg})")
|
|
492
|
+
return {nm: (data[nm] - hw, data[nm] + hw) for nm in names}, {"halfwidth"}
|
|
493
|
+
if _has_items(error):
|
|
494
|
+
entries = {str(k): v for k, v in _pairs(error)}
|
|
495
|
+
elif isinstance(error, (Sequence, np.ndarray)) and not isinstance(error, (str, bytes)):
|
|
496
|
+
listed = list(error)
|
|
497
|
+
if len(listed) != len(names):
|
|
498
|
+
raise ExplainError(
|
|
499
|
+
f"compare({arg}) lists {len(listed)} intervals for {len(names)} items.",
|
|
500
|
+
fix_hint=hint + " A list must follow the order of values.",
|
|
501
|
+
)
|
|
502
|
+
entries = dict(zip(names, listed, strict=True))
|
|
503
|
+
else:
|
|
504
|
+
raise ExplainError(
|
|
505
|
+
f"compare({arg}) must be a mapping, a list or one number, got {type(error).__name__}.",
|
|
506
|
+
fix_hint=hint,
|
|
507
|
+
)
|
|
508
|
+
extra = [k for k in entries if k not in data]
|
|
509
|
+
if extra:
|
|
510
|
+
raise ExplainError(
|
|
511
|
+
f"compare({arg}) names {extra[:4]!r}, which are not in values.",
|
|
512
|
+
fix_hint=f"Use names from: {', '.join(map(repr, names[:12]))}.",
|
|
513
|
+
)
|
|
514
|
+
errors: dict[str, tuple[float, float]] = {}
|
|
515
|
+
modes: set[str] = set()
|
|
516
|
+
for name in names:
|
|
517
|
+
if name not in entries:
|
|
518
|
+
raise ExplainError(
|
|
519
|
+
f"compare({arg}) has no entry for {name!r}.",
|
|
520
|
+
fix_hint=hint + f" Every item needs one, or omit `{arg}`.",
|
|
521
|
+
)
|
|
522
|
+
entry = entries[name]
|
|
523
|
+
if _is_number(entry):
|
|
524
|
+
hw = _halfwidth(entry, f"compare({arg}[{name!r}])")
|
|
525
|
+
errors[name] = (data[name] - hw, data[name] + hw)
|
|
526
|
+
modes.add("halfwidth")
|
|
527
|
+
continue
|
|
528
|
+
try:
|
|
529
|
+
pair = [v for v in entry] # type: ignore[union-attr]
|
|
530
|
+
except TypeError as exc:
|
|
531
|
+
raise ExplainError(
|
|
532
|
+
f"compare({arg}[{name!r}]) = {entry!r} is neither (low, high) nor a number.",
|
|
533
|
+
fix_hint=hint,
|
|
534
|
+
) from exc
|
|
535
|
+
if len(pair) != 2:
|
|
536
|
+
raise ExplainError(
|
|
537
|
+
f"compare({arg}[{name!r}]) has {len(pair)} numbers; an interval has two.",
|
|
538
|
+
fix_hint=hint,
|
|
539
|
+
)
|
|
540
|
+
low, high = (_to_float(v, f"compare({arg}[{name!r}])") for v in pair)
|
|
541
|
+
if not (math.isfinite(low) and math.isfinite(high)):
|
|
542
|
+
raise ExplainError(
|
|
543
|
+
f"compare({arg}[{name!r}]) = ({low}, {high}) is not finite.",
|
|
544
|
+
fix_hint=hint,
|
|
545
|
+
)
|
|
546
|
+
if not low <= data[name] <= high:
|
|
547
|
+
raise ExplainError(
|
|
548
|
+
f"compare({arg}[{name!r}]) = ({low}, {high}) does not bracket the value "
|
|
549
|
+
f"{data[name]}.",
|
|
550
|
+
fix_hint="Pass absolute (low, high) bounds, not +/- offsets; for a symmetric "
|
|
551
|
+
"interval pass one number, the half-width.",
|
|
552
|
+
)
|
|
553
|
+
errors[name] = (low, high)
|
|
554
|
+
modes.add("bounds")
|
|
555
|
+
return errors, modes
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _ordinal(k: int) -> str:
|
|
559
|
+
"""1 -> "1st", 2 -> "2nd", 11 -> "11th"."""
|
|
560
|
+
suffix = "th" if 10 <= k % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(k % 10, "th")
|
|
561
|
+
return f"{k}{suffix}"
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _compare_counts(n: object, names: Sequence[str]) -> dict[str, int]:
|
|
565
|
+
"""Read ``compare(n=...)``: {name: count} (or a list in the order of values)."""
|
|
566
|
+
hint = 'Give the number of observations behind each value, e.g. n={"Support": 84, "Legal": 61}.'
|
|
567
|
+
if _has_items(n):
|
|
568
|
+
entries = {str(k): v for k, v in _pairs(n)}
|
|
569
|
+
elif isinstance(n, (Sequence, np.ndarray)) and not isinstance(n, (str, bytes)):
|
|
570
|
+
listed = list(n)
|
|
571
|
+
if len(listed) != len(names):
|
|
572
|
+
raise ExplainError(
|
|
573
|
+
f"compare(n) lists {len(listed)} counts for {len(names)} items.",
|
|
574
|
+
fix_hint=hint + " A list must follow the order of values.",
|
|
575
|
+
)
|
|
576
|
+
entries = dict(zip(names, listed, strict=True))
|
|
577
|
+
else:
|
|
578
|
+
raise ExplainError(
|
|
579
|
+
f"compare(n) must be a mapping or a list of counts, got {type(n).__name__}.",
|
|
580
|
+
fix_hint=hint,
|
|
581
|
+
)
|
|
582
|
+
extra = [k for k in entries if k not in names]
|
|
583
|
+
if extra:
|
|
584
|
+
raise ExplainError(
|
|
585
|
+
f"compare(n) names {extra[:4]!r}, which are not in values.",
|
|
586
|
+
fix_hint=f"Use names from: {', '.join(map(repr, list(names)[:12]))}.",
|
|
587
|
+
)
|
|
588
|
+
counts: dict[str, int] = {}
|
|
589
|
+
for name in names:
|
|
590
|
+
if name not in entries or entries[name] is None:
|
|
591
|
+
continue
|
|
592
|
+
value = entries[name]
|
|
593
|
+
number = _to_float(value, f"compare(n[{name!r}])") if _is_number(value) else math.nan
|
|
594
|
+
if not (math.isfinite(number) and number >= 0 and float(number).is_integer()):
|
|
595
|
+
raise ExplainError(
|
|
596
|
+
f"compare(n[{name!r}]) = {value!r} is not a count.",
|
|
597
|
+
fix_hint=hint + " Each count is a whole number, 0 or more.",
|
|
598
|
+
)
|
|
599
|
+
counts[name] = int(number)
|
|
600
|
+
return counts
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
@_guarded("compare")
|
|
604
|
+
def compare(
|
|
605
|
+
values: (
|
|
606
|
+
Mapping[str, float]
|
|
607
|
+
| Mapping[str, Mapping[str, float | None]]
|
|
608
|
+
| Sequence[tuple[str, float]]
|
|
609
|
+
| Sequence[Mapping[str, Any]]
|
|
610
|
+
),
|
|
611
|
+
*,
|
|
612
|
+
name: str | None = None,
|
|
613
|
+
group: str | None = None,
|
|
614
|
+
value: str | None = None,
|
|
615
|
+
title: str | None = None,
|
|
616
|
+
label: str | None = None,
|
|
617
|
+
unit: str | None = None,
|
|
618
|
+
highlight: str | Sequence[str] | None = None,
|
|
619
|
+
baseline: str | None = None,
|
|
620
|
+
sort: bool | str = True,
|
|
621
|
+
zero: bool = True,
|
|
622
|
+
error: Mapping[str, Any] | Sequence[Any] | float | str | None = None,
|
|
623
|
+
error_label: str | None = None,
|
|
624
|
+
inner_error: Mapping[str, Any] | Sequence[Any] | float | str | None = None,
|
|
625
|
+
boost: Mapping[str, float] | str | None = None,
|
|
626
|
+
boost_label: str | None = None,
|
|
627
|
+
reference: float | tuple[float, str] | None = None,
|
|
628
|
+
log: bool = False,
|
|
629
|
+
fmt: str | None = None,
|
|
630
|
+
n: Mapping[str, int] | Sequence[int] | str | None = None,
|
|
631
|
+
show_delta: bool = False,
|
|
632
|
+
) -> Panel:
|
|
633
|
+
"""How do items differ in size? Sorted horizontal bars, grouped bars, or dot-interval marks.
|
|
634
|
+
|
|
635
|
+
``values`` maps item name to number (a dict, a pandas Series, or row-shaped
|
|
636
|
+
records / DataFrame with ``name=`` and ``value=`` columns). Pass a nested
|
|
637
|
+
mapping ``{category: {series: number}}`` (or tidy rows with ``group=``) for
|
|
638
|
+
a grouped multi-series comparison (e.g. multiple benchmarks × models).
|
|
639
|
+
Pass ``boost={name: extra}`` with ``boost_label=`` to stack a tinted
|
|
640
|
+
non-negative extension on each bar (e.g. standard score + extended thinking).
|
|
641
|
+
Bars start at zero; pass ``zero=False`` when zero is not meaningful (dot plot)
|
|
642
|
+
or ``log=True`` for values spanning decades. ``error`` + ``error_label`` draw
|
|
643
|
+
dot-and-interval marks; pass ``inner_error=`` alongside ``error=`` to draw a
|
|
644
|
+
thicker inner interval (e.g. 50% CI inside 95% CI, Kay & Hullman ggdist).
|
|
645
|
+
``baseline`` draws a control/incumbent in ink and states gaps against it in
|
|
646
|
+
``facts``; pass ``show_delta=True`` with ``baseline=`` to append inline signed
|
|
647
|
+
deltas beside each non-baseline value label.
|
|
648
|
+
"""
|
|
649
|
+
from .._tabular import (
|
|
650
|
+
extract_records,
|
|
651
|
+
is_tabular,
|
|
652
|
+
resolve_grouped_compare_table,
|
|
653
|
+
resolve_named_table,
|
|
654
|
+
)
|
|
655
|
+
from .compare_grouped import build_grouped_compare, is_nested_compare
|
|
656
|
+
|
|
657
|
+
if group is not None:
|
|
658
|
+
if (
|
|
659
|
+
boost is not None
|
|
660
|
+
or error is not None
|
|
661
|
+
or inner_error is not None
|
|
662
|
+
or n is not None
|
|
663
|
+
or show_delta
|
|
664
|
+
):
|
|
665
|
+
raise ExplainError(
|
|
666
|
+
"Grouped compare(group=...) cannot be combined with error=, inner_error=, boost=, n=, or show_delta=.",
|
|
667
|
+
fix_hint="Use separate compare() panels for intervals/boosts/deltas, or drop group=.",
|
|
668
|
+
)
|
|
669
|
+
nested = resolve_grouped_compare_table(values, name=name, group=group, value=value)
|
|
670
|
+
return build_grouped_compare(
|
|
671
|
+
nested,
|
|
672
|
+
title=title,
|
|
673
|
+
label=label,
|
|
674
|
+
unit=unit,
|
|
675
|
+
highlight=highlight,
|
|
676
|
+
baseline=baseline,
|
|
677
|
+
sort=sort if sort is not True else False,
|
|
678
|
+
zero=zero,
|
|
679
|
+
reference=reference,
|
|
680
|
+
log=log,
|
|
681
|
+
fmt=fmt,
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
if is_nested_compare(values):
|
|
685
|
+
if (
|
|
686
|
+
boost is not None
|
|
687
|
+
or error is not None
|
|
688
|
+
or inner_error is not None
|
|
689
|
+
or n is not None
|
|
690
|
+
or show_delta
|
|
691
|
+
):
|
|
692
|
+
raise ExplainError(
|
|
693
|
+
"Grouped compare() with nested dicts cannot be combined with error=, inner_error=, boost=, n=, or show_delta=.",
|
|
694
|
+
fix_hint="Use single-series compare() for intervals/boosts/deltas, or drop error=/inner_error=/boost=/n=/show_delta=.",
|
|
695
|
+
)
|
|
696
|
+
return build_grouped_compare(
|
|
697
|
+
values, # type: ignore[arg-type]
|
|
698
|
+
title=title,
|
|
699
|
+
label=label,
|
|
700
|
+
unit=unit,
|
|
701
|
+
highlight=highlight,
|
|
702
|
+
baseline=baseline,
|
|
703
|
+
sort=sort if sort is not True else False,
|
|
704
|
+
zero=zero,
|
|
705
|
+
reference=reference,
|
|
706
|
+
log=log,
|
|
707
|
+
fmt=fmt,
|
|
708
|
+
)
|
|
709
|
+
|
|
710
|
+
raw_values_obj = values
|
|
711
|
+
tabular = resolve_named_table(
|
|
712
|
+
values,
|
|
713
|
+
"compare(values)",
|
|
714
|
+
name=name,
|
|
715
|
+
value=value,
|
|
716
|
+
error=error,
|
|
717
|
+
n=n,
|
|
718
|
+
boost=boost,
|
|
719
|
+
form="compare",
|
|
720
|
+
)
|
|
721
|
+
if tabular is not None:
|
|
722
|
+
if inner_error is not None and is_tabular(raw_values_obj):
|
|
723
|
+
t_cols, t_rows = extract_records(raw_values_obj, what="compare(values)")
|
|
724
|
+
name_col = name or (t_cols[0] if t_cols else "")
|
|
725
|
+
if isinstance(inner_error, str) and inner_error in t_cols:
|
|
726
|
+
inner_error = {str(r.get(name_col, "")): r.get(inner_error) for r in t_rows}
|
|
727
|
+
elif (
|
|
728
|
+
isinstance(inner_error, (tuple, list))
|
|
729
|
+
and len(inner_error) == 2
|
|
730
|
+
and all(isinstance(c, str) and c in t_cols for c in inner_error)
|
|
731
|
+
):
|
|
732
|
+
lo_c, hi_c = str(inner_error[0]), str(inner_error[1])
|
|
733
|
+
inner_error = {
|
|
734
|
+
str(r.get(name_col, "")): (r.get(lo_c), r.get(hi_c)) for r in t_rows
|
|
735
|
+
}
|
|
736
|
+
values, error, n, boost = tabular
|
|
737
|
+
data = _named_values(values, "compare(values)")
|
|
738
|
+
names = list(data)
|
|
739
|
+
order = _sort_order(sort)
|
|
740
|
+
if len(names) > MAX_COMPARE_ITEMS:
|
|
741
|
+
if not _is_strict():
|
|
742
|
+
keep_req: list[str] = []
|
|
743
|
+
if highlight is not None:
|
|
744
|
+
req_hl = [highlight] if isinstance(highlight, str) else [str(h) for h in highlight]
|
|
745
|
+
keep_req.extend(nm for nm in req_hl if nm in data)
|
|
746
|
+
if baseline is not None and str(baseline) in data:
|
|
747
|
+
keep_req.append(str(baseline))
|
|
748
|
+
ranked_all = sorted(
|
|
749
|
+
names, key=lambda nm: data[nm], reverse=(order != "asc")
|
|
750
|
+
)
|
|
751
|
+
chosen: list[str] = list(dict.fromkeys(keep_req))
|
|
752
|
+
for nm in ranked_all:
|
|
753
|
+
if len(chosen) >= MAX_COMPARE_ITEMS:
|
|
754
|
+
break
|
|
755
|
+
if nm not in chosen:
|
|
756
|
+
chosen.append(nm)
|
|
757
|
+
chosen_set = set(chosen)
|
|
758
|
+
data = {nm: data[nm] for nm in names if nm in chosen_set}
|
|
759
|
+
_record_adjustment(f"compare(): trimmed {len(names)} items to top {len(data)}")
|
|
760
|
+
names = list(data)
|
|
761
|
+
else:
|
|
762
|
+
raise ExplainError(
|
|
763
|
+
f"compare() got {len(names)} items; a ranked list longer than "
|
|
764
|
+
f"{MAX_COMPARE_ITEMS} is scanned, not read.",
|
|
765
|
+
fix_hint=f"compare() takes at most {MAX_COMPARE_ITEMS} items: show the top 10 (say "
|
|
766
|
+
"so in the title, the rest in note=), use distribution() for the spread of many "
|
|
767
|
+
"values, or matrix() if the items form a grid.",
|
|
768
|
+
rule="too_many_items",
|
|
769
|
+
)
|
|
770
|
+
hl = _names(highlight, names)
|
|
771
|
+
base = _baseline_name(baseline, names, hl, "compare")
|
|
772
|
+
ref = _reference_line(reference, "compare(reference)")
|
|
773
|
+
errors: dict[str, tuple[float, float]] | None = None
|
|
774
|
+
modes: set[str] = set()
|
|
775
|
+
if error is not None:
|
|
776
|
+
errors, modes = _compare_intervals(error, data)
|
|
777
|
+
inner_errors: dict[str, tuple[float, float]] | None = None
|
|
778
|
+
if inner_error is not None:
|
|
779
|
+
if errors is None:
|
|
780
|
+
raise ExplainError(
|
|
781
|
+
"compare(inner_error=...) requires error= for the outer interval.",
|
|
782
|
+
fix_hint="Pass both error= (outer interval, e.g. 95% CI) and inner_error= (inner interval, e.g. 50% CI).",
|
|
783
|
+
)
|
|
784
|
+
inner_errors, _inner_modes = _compare_intervals(inner_error, data, arg="inner_error")
|
|
785
|
+
for nm in names:
|
|
786
|
+
out_lo, out_hi = errors[nm]
|
|
787
|
+
in_lo, in_hi = inner_errors[nm]
|
|
788
|
+
tol = 1e-9 * max(1.0, abs(out_lo), abs(out_hi))
|
|
789
|
+
if in_lo < out_lo - tol or in_hi > out_hi + tol:
|
|
790
|
+
raise ExplainError(
|
|
791
|
+
f"compare(inner_error[{nm!r}]) = ({in_lo}, {in_hi}) extends outside "
|
|
792
|
+
f"outer error ({out_lo}, {out_hi}).",
|
|
793
|
+
fix_hint="Ensure inner_error bounds lie within error bounds (e.g. 50% CI inside 95% CI).",
|
|
794
|
+
)
|
|
795
|
+
if show_delta:
|
|
796
|
+
if base is None:
|
|
797
|
+
raise ExplainError(
|
|
798
|
+
"compare(show_delta=True) requires baseline= to compute inline deltas against.",
|
|
799
|
+
fix_hint='Pass baseline="<item>" alongside show_delta=True.',
|
|
800
|
+
)
|
|
801
|
+
if boost is not None:
|
|
802
|
+
raise ExplainError(
|
|
803
|
+
"compare(show_delta=True) cannot be combined with boost=.",
|
|
804
|
+
fix_hint="Drop either show_delta=True or boost= so value labels stay unambiguous.",
|
|
805
|
+
)
|
|
806
|
+
counts = _compare_counts(n, names) if n is not None else {}
|
|
807
|
+
boost_map: dict[str, float] | None = None
|
|
808
|
+
if boost is not None:
|
|
809
|
+
if not zero or log or errors is not None:
|
|
810
|
+
raise ExplainError(
|
|
811
|
+
"compare(boost=...) draws stacked bar extensions and requires zero=True, log=False, and no error=.",
|
|
812
|
+
fix_hint="Remove zero=False / log=True / error= when using boost=.",
|
|
813
|
+
)
|
|
814
|
+
if min(data.values()) < 0:
|
|
815
|
+
raise ExplainError(
|
|
816
|
+
"compare(boost=...) requires non-negative base values.",
|
|
817
|
+
fix_hint="Use compare() without boost= for signed/diverging values.",
|
|
818
|
+
)
|
|
819
|
+
raw_boost = _named_values(boost, "compare(boost)", allow_nan=True)
|
|
820
|
+
extra_b = [k for k in raw_boost if k not in data]
|
|
821
|
+
if extra_b:
|
|
822
|
+
raise ExplainError(
|
|
823
|
+
f"compare(boost) names {extra_b[:4]!r}, which are not in values.",
|
|
824
|
+
fix_hint=f"Use names from: {', '.join(map(repr, names[:12]))}.",
|
|
825
|
+
)
|
|
826
|
+
boost_map = {}
|
|
827
|
+
for nm in names:
|
|
828
|
+
bv = raw_boost.get(nm, 0.0)
|
|
829
|
+
if not math.isfinite(bv):
|
|
830
|
+
bv = 0.0
|
|
831
|
+
if bv < 0:
|
|
832
|
+
raise ExplainError(
|
|
833
|
+
f"compare(boost[{nm!r}]) = {bv!r} must be >= 0.",
|
|
834
|
+
fix_hint="boost= adds a non-negative extension to each bar; pass 0 for items with no boost.",
|
|
835
|
+
)
|
|
836
|
+
boost_map[nm] = float(bv)
|
|
837
|
+
if log:
|
|
838
|
+
lows = [errors[nm][0] for nm in names] if errors else []
|
|
839
|
+
if min([*data.values(), *lows, *([ref[0]] if ref else [])]) <= 0:
|
|
840
|
+
raise ExplainError(
|
|
841
|
+
"compare(log=True) needs strictly positive values (and interval bounds and "
|
|
842
|
+
"reference).",
|
|
843
|
+
fix_hint="Drop log=True, or remove the non-positive items and say so in note=.",
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
issues: list[dict[str, Any]] = []
|
|
847
|
+
if len(names) > COMFORTABLE_COMPARE_ITEMS:
|
|
848
|
+
issues.append(
|
|
849
|
+
_issue(
|
|
850
|
+
"many_items",
|
|
851
|
+
"warning",
|
|
852
|
+
f"{len(names)} items is a long list for one glance.",
|
|
853
|
+
"Show the top 10 (say so in the title) and pass the rest as a sentence in note=.",
|
|
854
|
+
)
|
|
855
|
+
)
|
|
856
|
+
if zero and not log and errors is None and min(data.values()) > 0:
|
|
857
|
+
lo, hi = min(data.values()), max(data.values())
|
|
858
|
+
if hi > 0 and (hi - lo) / hi < 0.1 and len(names) > 1:
|
|
859
|
+
issues.append(
|
|
860
|
+
_issue(
|
|
861
|
+
"differences_invisible",
|
|
862
|
+
"warning",
|
|
863
|
+
f"All values lie within {100 * (hi - lo) / hi:.0f}% of each other, so "
|
|
864
|
+
"zero-based bars will look identical.",
|
|
865
|
+
"If the small differences are the point, pass zero=False (dot plot) and "
|
|
866
|
+
"say in the title that the differences are small.",
|
|
867
|
+
)
|
|
868
|
+
)
|
|
869
|
+
if errors is not None and not error_label:
|
|
870
|
+
issues.append(_interval_issue("compare", "error", "error_label"))
|
|
871
|
+
if boost_map is not None and not boost_label:
|
|
872
|
+
issues.append(
|
|
873
|
+
_issue(
|
|
874
|
+
"boost_unlabelled",
|
|
875
|
+
"warning",
|
|
876
|
+
"compare(boost=...) draws a tinted bar extension without saying what it represents.",
|
|
877
|
+
'Pass boost_label=, e.g. boost_label="Extended thinking".',
|
|
878
|
+
)
|
|
879
|
+
)
|
|
880
|
+
|
|
881
|
+
eff_data = (
|
|
882
|
+
{nm: data[nm] + boost_map[nm] for nm in names} if boost_map is not None else data
|
|
883
|
+
)
|
|
884
|
+
if order == "desc":
|
|
885
|
+
names = sorted(names, key=lambda nm: eff_data[nm], reverse=True)
|
|
886
|
+
elif order == "asc":
|
|
887
|
+
names = sorted(names, key=lambda nm: eff_data[nm])
|
|
888
|
+
vals = [data[nm] for nm in names]
|
|
889
|
+
boost_vals = [boost_map[nm] for nm in names] if boost_map is not None else None
|
|
890
|
+
totals = [eff_data[nm] for nm in names]
|
|
891
|
+
fmt_fn = _formatter([*vals, *totals], fmt, unit=unit, log=log)
|
|
892
|
+
if boost_vals is not None:
|
|
893
|
+
pos_boosts = [b for b in boost_vals if b > 0]
|
|
894
|
+
b_fmt = _formatter(pos_boosts or [0.0], fmt, unit=unit)
|
|
895
|
+
labels = []
|
|
896
|
+
for i, (tot_v, b_v) in enumerate(zip(totals, boost_vals, strict=True)):
|
|
897
|
+
t_txt = _with_unit(fmt_fn(tot_v), unit) if (i == 0 or _inline_unit(unit)) else fmt_fn(tot_v)
|
|
898
|
+
labels.append(f"{t_txt} (+{b_fmt(b_v)})" if b_v > 0 else t_txt)
|
|
899
|
+
elif show_delta and base is not None:
|
|
900
|
+
deltas = [data[nm] - data[base] for nm in names if nm != base]
|
|
901
|
+
d_fmt = _formatter(deltas or [0.0], fmt, unit=unit)
|
|
902
|
+
labels = []
|
|
903
|
+
for i, (nm, v) in enumerate(zip(names, vals, strict=True)):
|
|
904
|
+
base_txt = _with_unit(fmt_fn(v), unit) if (i == 0 or _inline_unit(unit)) else fmt_fn(v)
|
|
905
|
+
if nm != base:
|
|
906
|
+
labels.append(f"{base_txt} ({_signed(d_fmt(v - data[base]))})")
|
|
907
|
+
else:
|
|
908
|
+
labels.append(base_txt)
|
|
909
|
+
else:
|
|
910
|
+
labels = [
|
|
911
|
+
_with_unit(fmt_fn(v), unit) if (i == 0 or _inline_unit(unit)) else fmt_fn(v)
|
|
912
|
+
for i, v in enumerate(vals)
|
|
913
|
+
]
|
|
914
|
+
|
|
915
|
+
# Values of both signs (changes, differences): positives carry a "+", and the
|
|
916
|
+
# highlighted items are placed against zero, not against their neighbours.
|
|
917
|
+
diverging = min(data.values()) < 0 < max(data.values())
|
|
918
|
+
# zero=False says zero is not meaningful (wavelengths, temperatures, positions):
|
|
919
|
+
# ratios of the values mean nothing there; differences still do. A log axis keeps them.
|
|
920
|
+
ratios = zero or log
|
|
921
|
+
|
|
922
|
+
def _u(v: float, f: Callable[[float], str] = fmt_fn) -> str:
|
|
923
|
+
text = f(v)
|
|
924
|
+
return _with_unit(_signed(text) if diverging else text, unit)
|
|
925
|
+
|
|
926
|
+
def _nn(name: str) -> str:
|
|
927
|
+
return f" (n={counts[name]})" if name in counts else ""
|
|
928
|
+
|
|
929
|
+
descending = sorted(data, key=lambda nm: data[nm], reverse=True)
|
|
930
|
+
ranking = names if order != "given" else descending
|
|
931
|
+
rank_word = "lowest first" if order == "asc" else "highest first"
|
|
932
|
+
top, bottom = descending[0], descending[-1]
|
|
933
|
+
facts = [f"highest: {top} {_u(data[top])}{_nn(top)}"]
|
|
934
|
+
if len(descending) > 1:
|
|
935
|
+
facts.append(f"lowest: {bottom} {_u(data[bottom])}{_nn(bottom)}")
|
|
936
|
+
if ratios and all(v > 0 for v in data.values()):
|
|
937
|
+
facts.append(
|
|
938
|
+
f"highest/lowest ratio: {_ratio_text(data[top] / data[bottom])} "
|
|
939
|
+
"(from unrounded values)"
|
|
940
|
+
)
|
|
941
|
+
else:
|
|
942
|
+
span_fmt = _formatter([data[top] - data[bottom]], fmt, unit=unit)
|
|
943
|
+
# A spread is a width: no sign (even from a signed fmt), in points for "%".
|
|
944
|
+
spread = _diff_with_unit(_unsigned(span_fmt(data[top] - data[bottom])), unit)
|
|
945
|
+
facts.append(f"range: {_u(data[bottom])} to {_u(data[top])} (spread {spread})")
|
|
946
|
+
if ratios and not diverging and len(descending) > 2:
|
|
947
|
+
second = descending[1]
|
|
948
|
+
if data[second] > 0 and data[top] > 0 and data[top] / data[second] >= 1.1:
|
|
949
|
+
facts.append(
|
|
950
|
+
f"{top} is {_ratio_text(data[top] / data[second])} the next highest "
|
|
951
|
+
f"({second} {_u(data[second])})"
|
|
952
|
+
)
|
|
953
|
+
diffs: list[tuple[str, float, str, float]] = []
|
|
954
|
+
for item in hl:
|
|
955
|
+
if ref is not None:
|
|
956
|
+
diffs.append((item, data[item] - ref[0], ref[1] or "reference", ref[0]))
|
|
957
|
+
elif base is None and not diverging:
|
|
958
|
+
# With a baseline every item is stated against it below; with values of both
|
|
959
|
+
# signs each highlighted item is placed against zero instead.
|
|
960
|
+
others = [nm for nm in ranking if nm not in hl]
|
|
961
|
+
if others:
|
|
962
|
+
diffs.append((item, data[item] - data[others[0]], others[0], data[others[0]]))
|
|
963
|
+
diff_fmt = _formatter([d[1] for d in diffs], fmt, unit=unit)
|
|
964
|
+
|
|
965
|
+
if errors is not None:
|
|
966
|
+
bound_fmt = _formatter(
|
|
967
|
+
# On a log axis the bounds share the values' notation.
|
|
968
|
+
[*(vals if log else []), *(v for pair in errors.values() for v in pair)],
|
|
969
|
+
fmt,
|
|
970
|
+
unit=unit,
|
|
971
|
+
log=log,
|
|
972
|
+
)
|
|
973
|
+
|
|
974
|
+
def _span(nm: str) -> str:
|
|
975
|
+
lo_v, hi_v = errors[nm] # type: ignore[index]
|
|
976
|
+
return _range_with_unit(bound_fmt(lo_v), bound_fmt(hi_v), unit)
|
|
977
|
+
|
|
978
|
+
ref_shown = ref_named = ""
|
|
979
|
+
if ref is not None:
|
|
980
|
+
# The reference as the caller gave it ("1×", not "1.00×" from the values' digits).
|
|
981
|
+
ref_shown = _with_unit(_formatter([ref[0]], log=log)(ref[0]), unit)
|
|
982
|
+
ref_named = f" ({ref[1]})" if ref[1] else ""
|
|
983
|
+
|
|
984
|
+
def _vs_reference(nm: str) -> str:
|
|
985
|
+
"""Where an interval lies against the reference: "above", "below" or "includes"."""
|
|
986
|
+
lo_v, hi_v = errors[nm] # type: ignore[index]
|
|
987
|
+
return "above" if lo_v > ref[0] else "below" if hi_v < ref[0] else "includes" # type: ignore[index]
|
|
988
|
+
|
|
989
|
+
below_zero = [nm for nm in reversed(descending) if data[nm] < 0] # most negative first
|
|
990
|
+
above_zero = [nm for nm in descending if data[nm] > 0]
|
|
991
|
+
|
|
992
|
+
def _against_zero(nm: str) -> str:
|
|
993
|
+
""""furthest of the 3 below zero", "2nd furthest of the 9 above zero"."""
|
|
994
|
+
if data[nm] == 0:
|
|
995
|
+
return "at zero"
|
|
996
|
+
group, word = (below_zero, "below") if data[nm] < 0 else (above_zero, "above")
|
|
997
|
+
if len(group) == 1:
|
|
998
|
+
return f"the only one {word} zero"
|
|
999
|
+
k = group.index(nm) + 1
|
|
1000
|
+
far = "furthest" if k == 1 else f"{_ordinal(k)} furthest"
|
|
1001
|
+
return f"{far} of the {len(group)} {word} zero"
|
|
1002
|
+
|
|
1003
|
+
ci_name = error_label if error_label and len(error_label) <= 24 else "interval"
|
|
1004
|
+
# Alt text: the extremes, then each highlighted item (or each item against the baseline).
|
|
1005
|
+
alt_facts = [f for f in facts if f.startswith(("highest: ", "lowest: "))]
|
|
1006
|
+
for item in hl:
|
|
1007
|
+
detail = f"n={counts[item]}; " if item in counts else ""
|
|
1008
|
+
text = (
|
|
1009
|
+
f"{item}: {_u(data[item])} ({detail}rank {ranking.index(item) + 1} of "
|
|
1010
|
+
f"{len(ranking)}, {rank_word})"
|
|
1011
|
+
)
|
|
1012
|
+
for d_name, d_value, other, other_value in diffs:
|
|
1013
|
+
if d_name != item:
|
|
1014
|
+
continue
|
|
1015
|
+
if log:
|
|
1016
|
+
if errors is not None and ref is not None and ref[0] == 1:
|
|
1017
|
+
continue # the value is already its ratio to 1: the interval says more
|
|
1018
|
+
# On a log axis items differ by factors: a ratio, never a signed one
|
|
1019
|
+
# ("6.0× no change", "0.39× no change"), not "+6.02× vs no change".
|
|
1020
|
+
text += f"; {_ratio_text(data[item] / other_value)} {other} ({_u(other_value)})"
|
|
1021
|
+
else:
|
|
1022
|
+
text += (
|
|
1023
|
+
f"; {_diff_with_unit(_signed(diff_fmt(d_value)), unit)} vs {other} "
|
|
1024
|
+
f"({_u(other_value)})"
|
|
1025
|
+
)
|
|
1026
|
+
if diverging and ref is None and base is None:
|
|
1027
|
+
text += f"; {_against_zero(item)}"
|
|
1028
|
+
if errors is not None and ref is not None:
|
|
1029
|
+
side = _vs_reference(item)
|
|
1030
|
+
where = (
|
|
1031
|
+
f"includes {ref_shown}{ref_named}"
|
|
1032
|
+
if side == "includes"
|
|
1033
|
+
else f"{side} {ref_shown}{ref_named}"
|
|
1034
|
+
)
|
|
1035
|
+
text += f"; {ci_name} {_span(item)}, {where}"
|
|
1036
|
+
facts.append(text)
|
|
1037
|
+
if base is None:
|
|
1038
|
+
alt_facts.append(text)
|
|
1039
|
+
if diverging and hl:
|
|
1040
|
+
rest = [nm for nm in ranking if nm not in hl and nm != base]
|
|
1041
|
+
if rest:
|
|
1042
|
+
lo_nm = min(rest, key=lambda nm: data[nm])
|
|
1043
|
+
hi_nm = max(rest, key=lambda nm: data[nm])
|
|
1044
|
+
if len(rest) == 1:
|
|
1045
|
+
facts.append(f"the other item, {lo_nm}, is {_u(data[lo_nm])}")
|
|
1046
|
+
else:
|
|
1047
|
+
facts.append(
|
|
1048
|
+
f"the other {len(rest)} are within {_u(data[lo_nm])} to {_u(data[hi_nm])}"
|
|
1049
|
+
)
|
|
1050
|
+
if base is not None:
|
|
1051
|
+
compared = (hl or [nm for nm in ranking if nm != base])[:6]
|
|
1052
|
+
vs_fmt = _formatter([data[nm] - data[base] for nm in compared], fmt, unit=unit)
|
|
1053
|
+
for item in compared:
|
|
1054
|
+
if log:
|
|
1055
|
+
facts.append(
|
|
1056
|
+
f"{item} is {_vs_text(data[item], data[base], unit=unit, diff_fmt=vs_fmt, log=True)} "
|
|
1057
|
+
f"{base} ({_u(data[item])} vs {_u(data[base])})"
|
|
1058
|
+
)
|
|
1059
|
+
else:
|
|
1060
|
+
facts.append(
|
|
1061
|
+
f"{item} {_u(data[item])} vs {base} {_u(data[base])}: "
|
|
1062
|
+
f"{_vs_text(data[item], data[base], unit=unit, diff_fmt=vs_fmt, relative=ratios)}"
|
|
1063
|
+
)
|
|
1064
|
+
alt_facts.append(facts[-1])
|
|
1065
|
+
if errors is not None:
|
|
1066
|
+
pairs: list[tuple[str, str]] = []
|
|
1067
|
+
if base is not None:
|
|
1068
|
+
pairs = [(nm, base) for nm in (hl or [nm for nm in ranking if nm != base])[:6]]
|
|
1069
|
+
elif hl and ref is None:
|
|
1070
|
+
# Each highlighted interval against every other item's: which overlap it and
|
|
1071
|
+
# which do not ("outlier, or the bottom of a spread?").
|
|
1072
|
+
for a in hl:
|
|
1073
|
+
a_lo, a_hi = errors[a]
|
|
1074
|
+
others = [nm for nm in ranking if nm != a]
|
|
1075
|
+
over = [nm for nm in others if errors[nm][0] <= a_hi and a_lo <= errors[nm][1]]
|
|
1076
|
+
apart = [nm for nm in others if nm not in over]
|
|
1077
|
+
listed = [
|
|
1078
|
+
f"overlaps {_and_list([f'{nm} {_span(nm)}' for nm in over])}" if over else "",
|
|
1079
|
+
f"does not overlap {_or_list([f'{nm} {_span(nm)}' for nm in apart])}"
|
|
1080
|
+
if apart
|
|
1081
|
+
else "",
|
|
1082
|
+
]
|
|
1083
|
+
facts.append(f"{a} {_span(a)} " + "; ".join(t for t in listed if t))
|
|
1084
|
+
elif len(ranking) > 1 and ref is None:
|
|
1085
|
+
pairs = [(ranking[1], ranking[0])]
|
|
1086
|
+
for a, b in pairs:
|
|
1087
|
+
(a_lo, a_hi), (b_lo, b_hi) = errors[a], errors[b]
|
|
1088
|
+
verb = "overlaps" if (a_lo <= b_hi and b_lo <= a_hi) else "does not overlap"
|
|
1089
|
+
facts.append(f"{a} {_span(a)} {verb} {b} {_span(b)}")
|
|
1090
|
+
if ref is not None:
|
|
1091
|
+
# Every interval against the reference, not against the first item.
|
|
1092
|
+
sides: dict[str, list[str]] = {"above": [], "includes": [], "below": []}
|
|
1093
|
+
for nm in ranking:
|
|
1094
|
+
sides[_vs_reference(nm)].append(nm)
|
|
1095
|
+
parts = [
|
|
1096
|
+
f"{phrase} for {_and_list(sides[key])}"
|
|
1097
|
+
for key, phrase in (
|
|
1098
|
+
("above", "entirely above"),
|
|
1099
|
+
("includes", "include it"),
|
|
1100
|
+
("below", "entirely below"),
|
|
1101
|
+
)
|
|
1102
|
+
if sides[key]
|
|
1103
|
+
]
|
|
1104
|
+
facts.append(f"intervals against {ref_shown}{ref_named}: " + "; ".join(parts))
|
|
1105
|
+
facts.append(_interval_mode_text(modes, "intervals"))
|
|
1106
|
+
|
|
1107
|
+
what = label or "values"
|
|
1108
|
+
describe = (
|
|
1109
|
+
f"{'Dot plot' if (not zero or errors or log) else 'Bar chart'} of {what} for {len(names)} items"
|
|
1110
|
+
+ (f", in {unit}" if unit else "")
|
|
1111
|
+
+ (" on a log scale" if log else "")
|
|
1112
|
+
+ (f", with intervals ({error_label})" if errors and error_label else "")
|
|
1113
|
+
+ (" and nested inner interval" if inner_errors is not None else "")
|
|
1114
|
+
)
|
|
1115
|
+
notes = [
|
|
1116
|
+
nt
|
|
1117
|
+
for nt in (
|
|
1118
|
+
"log scale" if log else None,
|
|
1119
|
+
f"intervals: {error_label}" if errors and error_label else None,
|
|
1120
|
+
"thick bar: inner interval" if inner_errors is not None else None,
|
|
1121
|
+
)
|
|
1122
|
+
if nt
|
|
1123
|
+
]
|
|
1124
|
+
if boost_map is not None:
|
|
1125
|
+
b_label_txt = boost_label or "boost"
|
|
1126
|
+
notes.append(f"tinted extension: {b_label_txt}")
|
|
1127
|
+
best_tot = max(names, key=lambda nm: eff_data[nm])
|
|
1128
|
+
best_gain = max(names, key=lambda nm: boost_map[nm])
|
|
1129
|
+
facts.append(
|
|
1130
|
+
f"with {b_label_txt}: highest total {best_tot} {_u(eff_data[best_tot])} "
|
|
1131
|
+
f"(base {_u(data[best_tot])} + {fmt_fn(boost_map[best_tot])})"
|
|
1132
|
+
)
|
|
1133
|
+
if boost_map[best_gain] > 0:
|
|
1134
|
+
facts.append(
|
|
1135
|
+
f"largest {b_label_txt} gain: {best_gain} (+{_diff_with_unit(fmt_fn(boost_map[best_gain]), unit)})"
|
|
1136
|
+
)
|
|
1137
|
+
panel = _bar_panel(
|
|
1138
|
+
kind="compare",
|
|
1139
|
+
names=names,
|
|
1140
|
+
values=vals,
|
|
1141
|
+
highlight=hl,
|
|
1142
|
+
labels=labels,
|
|
1143
|
+
title=title,
|
|
1144
|
+
label=label,
|
|
1145
|
+
unit=unit,
|
|
1146
|
+
spec=_base_spec(
|
|
1147
|
+
title,
|
|
1148
|
+
label,
|
|
1149
|
+
unit,
|
|
1150
|
+
values={nm: data[nm] for nm in data},
|
|
1151
|
+
highlight=hl or None,
|
|
1152
|
+
baseline=base,
|
|
1153
|
+
sort=sort,
|
|
1154
|
+
zero=zero,
|
|
1155
|
+
error=_jsonable(error) if errors else None,
|
|
1156
|
+
error_label=error_label,
|
|
1157
|
+
inner_error=_jsonable(inner_error) if inner_errors is not None else None,
|
|
1158
|
+
boost={nm: boost_map[nm] for nm in data} if boost_map is not None else None,
|
|
1159
|
+
boost_label=boost_label,
|
|
1160
|
+
reference=list(ref) if ref else None,
|
|
1161
|
+
log=log or None,
|
|
1162
|
+
fmt=fmt,
|
|
1163
|
+
n=dict(counts) or None,
|
|
1164
|
+
show_delta=True if show_delta else None,
|
|
1165
|
+
),
|
|
1166
|
+
facts=facts,
|
|
1167
|
+
describe=describe,
|
|
1168
|
+
dots=(not zero) or errors is not None or log,
|
|
1169
|
+
errors=errors,
|
|
1170
|
+
inner_errors=inner_errors,
|
|
1171
|
+
reference=ref,
|
|
1172
|
+
issues=issues,
|
|
1173
|
+
log=log,
|
|
1174
|
+
measure_note="; ".join(notes) or None,
|
|
1175
|
+
baseline=base,
|
|
1176
|
+
counts=counts,
|
|
1177
|
+
boosts=boost_vals,
|
|
1178
|
+
)
|
|
1179
|
+
panel.alt_facts = alt_facts
|
|
1180
|
+
return panel
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
@_guarded("share")
|
|
1184
|
+
def share(
|
|
1185
|
+
parts: Mapping[str, float] | Sequence[tuple[str, float]] | Sequence[Mapping[str, Any]],
|
|
1186
|
+
*,
|
|
1187
|
+
name: str | None = None,
|
|
1188
|
+
value: str | None = None,
|
|
1189
|
+
title: str | None = None,
|
|
1190
|
+
label: str | None = None,
|
|
1191
|
+
unit: str | None = None,
|
|
1192
|
+
highlight: str | Sequence[str] | None = None,
|
|
1193
|
+
top: int = 7,
|
|
1194
|
+
fmt: str | None = None,
|
|
1195
|
+
) -> Panel:
|
|
1196
|
+
"""What makes up the total? Sorted bars of each part's percentage (never a pie).
|
|
1197
|
+
|
|
1198
|
+
Parts beyond the ``top`` largest are folded into one muted "Other" bar.
|
|
1199
|
+
``label`` and ``unit`` describe the total, which is stated above the bars.
|
|
1200
|
+
Accepts dicts, Series, or row-shaped data with ``name=`` and ``value=``.
|
|
1201
|
+
"""
|
|
1202
|
+
from .._tabular import resolve_named_table
|
|
1203
|
+
|
|
1204
|
+
tabular = resolve_named_table(
|
|
1205
|
+
parts,
|
|
1206
|
+
"share(parts)",
|
|
1207
|
+
name=name,
|
|
1208
|
+
value=value,
|
|
1209
|
+
form="share",
|
|
1210
|
+
)
|
|
1211
|
+
if tabular is not None:
|
|
1212
|
+
parts = tabular[0]
|
|
1213
|
+
data = _named_values(parts, "share(parts)")
|
|
1214
|
+
if min(data.values()) < 0:
|
|
1215
|
+
raise ExplainError(
|
|
1216
|
+
"share() needs non-negative parts; a negative part has no share of a total.",
|
|
1217
|
+
fix_hint="Use compare() for signed values.",
|
|
1218
|
+
)
|
|
1219
|
+
total = sum(data.values())
|
|
1220
|
+
if total <= 0:
|
|
1221
|
+
raise ExplainError("share() parts sum to zero.", fix_hint="Pass positive parts.")
|
|
1222
|
+
if top < 2:
|
|
1223
|
+
raise ExplainError("share(top) must be at least 2.", fix_hint="Use top=5 or similar.")
|
|
1224
|
+
ranked = sorted(data, key=lambda nm: data[nm], reverse=True)
|
|
1225
|
+
kept = ranked if len(ranked) <= top + 1 else ranked[:top]
|
|
1226
|
+
rest = [nm for nm in ranked if nm not in kept]
|
|
1227
|
+
other_name = f"Other ({len(rest)})"
|
|
1228
|
+
if highlight is not None and rest:
|
|
1229
|
+
req = [highlight] if isinstance(highlight, str) else [str(h) for h in highlight]
|
|
1230
|
+
folded = [nm for nm in req if nm in rest]
|
|
1231
|
+
if folded:
|
|
1232
|
+
needed = max(ranked.index(nm) + 1 for nm in folded)
|
|
1233
|
+
if not _is_strict() and needed <= 12:
|
|
1234
|
+
top = needed
|
|
1235
|
+
kept = ranked if len(ranked) <= top + 1 else ranked[:top]
|
|
1236
|
+
rest = [nm for nm in ranked if nm not in kept]
|
|
1237
|
+
other_name = f"Other ({len(rest)})"
|
|
1238
|
+
_record_adjustment(f"share(): raised top={top} so {folded!r} stays out of Other")
|
|
1239
|
+
else:
|
|
1240
|
+
raise ExplainError(
|
|
1241
|
+
f"share(highlight) names {folded!r} that were folded into '{other_name}' (top={top}).",
|
|
1242
|
+
fix_hint=f"Increase top={needed} to keep them out of Other, or highlight from: "
|
|
1243
|
+
f"{', '.join(map(repr, kept[:12]))}.",
|
|
1244
|
+
)
|
|
1245
|
+
hl = _names(highlight, kept, "share(highlight)")
|
|
1246
|
+
|
|
1247
|
+
names = list(kept)
|
|
1248
|
+
pct = [100.0 * data[nm] / total for nm in kept]
|
|
1249
|
+
if rest:
|
|
1250
|
+
names.append(other_name)
|
|
1251
|
+
pct.append(100.0 * sum(data[nm] for nm in rest) / total)
|
|
1252
|
+
if fmt is not None:
|
|
1253
|
+
pct_fmt = _formatter(pct, fmt, unit="%")
|
|
1254
|
+
else:
|
|
1255
|
+
decimals = 0 if max(pct) >= 10 else 1
|
|
1256
|
+
|
|
1257
|
+
def pct_fmt(v: float) -> str:
|
|
1258
|
+
text = f"{v:.{decimals}f}"
|
|
1259
|
+
return _sig_text(v, 2) if (v != 0 and _shows_zero(text)) else text
|
|
1260
|
+
|
|
1261
|
+
labels = [f"{pct_fmt(v)}%" for v in pct]
|
|
1262
|
+
|
|
1263
|
+
total_fmt = _formatter([total], unit=unit)
|
|
1264
|
+
total_text = _with_unit(total_fmt(total), unit)
|
|
1265
|
+
# "Share of energy", but a label that already says share is kept: never "Share of Share".
|
|
1266
|
+
whole = label if (label and label.strip().lower().startswith("share")) else (
|
|
1267
|
+
f"Share of {label or 'total'}"
|
|
1268
|
+
)
|
|
1269
|
+
measure = f"{whole} ({total_text} in all)"
|
|
1270
|
+
cumulative = np.cumsum(pct[: len(kept)])
|
|
1271
|
+
facts = [f"total: {total_text}", f"largest: {kept[0]} {labels[0]}"]
|
|
1272
|
+
for item in hl:
|
|
1273
|
+
part_fmt = _formatter([data[item]], unit=unit)
|
|
1274
|
+
facts.append(
|
|
1275
|
+
f"{item}: {labels[kept.index(item)]} ({_with_unit(part_fmt(data[item]), unit)})"
|
|
1276
|
+
)
|
|
1277
|
+
if len(kept) >= 3:
|
|
1278
|
+
facts.append(f"top 3 together: {cumulative[2]:.0f}%")
|
|
1279
|
+
if rest:
|
|
1280
|
+
facts.append(f"{len(rest)} smaller parts folded into Other: {labels[-1]}")
|
|
1281
|
+
if len(hl) >= 2:
|
|
1282
|
+
together = sum(data[nm] for nm in hl)
|
|
1283
|
+
facts.append(
|
|
1284
|
+
f"{_and_list(hl)} together: {pct_fmt(100.0 * together / total)}% "
|
|
1285
|
+
f"({_with_unit(_formatter([together], unit=unit)(together), unit)})"
|
|
1286
|
+
)
|
|
1287
|
+
|
|
1288
|
+
return _bar_panel(
|
|
1289
|
+
kind="share",
|
|
1290
|
+
names=names,
|
|
1291
|
+
values=pct,
|
|
1292
|
+
highlight=hl,
|
|
1293
|
+
labels=labels,
|
|
1294
|
+
title=title,
|
|
1295
|
+
label=measure,
|
|
1296
|
+
unit=None,
|
|
1297
|
+
spec=_base_spec(
|
|
1298
|
+
title, label, unit, parts=dict(data), highlight=hl or None, top=top, fmt=fmt
|
|
1299
|
+
),
|
|
1300
|
+
facts=facts,
|
|
1301
|
+
describe=f"Bar chart of each part's share of {label or 'the total'} ({len(data)} parts)"
|
|
1302
|
+
if whole.startswith("Share of")
|
|
1303
|
+
else f"Bar chart of {label} by part ({len(data)} parts)",
|
|
1304
|
+
dots=False,
|
|
1305
|
+
errors=None,
|
|
1306
|
+
reference=None,
|
|
1307
|
+
muted_names=(other_name,) if rest else (),
|
|
1308
|
+
)
|