@samizdata/mozaic 0.3.0 → 0.4.1
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.
- package/README.md +1 -1
- package/dist/recipes/PercentileChart.svelte +452 -0
- package/dist/recipes/PercentileChart.svelte.d.ts +103 -0
- package/dist/recipes/index.d.ts +2 -1
- package/dist/recipes/index.js +3 -1
- package/dist/transforms/index.d.ts +1 -0
- package/dist/transforms/index.js +1 -0
- package/dist/transforms/percentile.d.ts +30 -0
- package/dist/transforms/percentile.js +34 -0
- package/package.json +1 -1
- package/src/lib/recipes/PercentileChart.svelte +452 -0
- package/src/lib/recipes/index.ts +3 -1
package/README.md
CHANGED
|
@@ -40,6 +40,6 @@ pnpm add mozaic d3-scale d3-array d3-shape
|
|
|
40
40
|
| `@samizdata/mozaic/locale` | `createLocale` (`en`, `ro`, `ru`) |
|
|
41
41
|
| `@samizdata/mozaic/embed` | `Embed`, `useEmbedParams`, `embedCode`, `hostScript`, `observeHeight` |
|
|
42
42
|
| `@samizdata/mozaic/export` | `figureToSvg`, `downloadSvg`, `downloadPng`, `figureToPng` |
|
|
43
|
-
| `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`
|
|
43
|
+
| `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`, `PercentileChart` |
|
|
44
44
|
|
|
45
45
|
Requires Svelte 5.57+. The full guides, API reference and gallery are in the repository's docs site.
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Recipe: "how do you compare?". One strip per group showing its published
|
|
4
|
+
percentiles (a line across the range, a thicker band for the middle half, a
|
|
5
|
+
dot per percentile and a large dot for the median), a "you" line at the
|
|
6
|
+
reader's value, and the reader's estimated percentile in each group at the
|
|
7
|
+
right. Readers set the value with a number box, a slider, or by clicking or
|
|
8
|
+
dragging on the strips. Percentiles are interpolated linearly between the
|
|
9
|
+
published points (see `percentileRank` in `@samizdata/mozaic/transforms`).
|
|
10
|
+
In print the controls are hidden and the chart shows the starting value.
|
|
11
|
+
Use it as is, or run `mozaic eject PercentileChart` to copy this file into
|
|
12
|
+
your project and change anything.
|
|
13
|
+
-->
|
|
14
|
+
<script lang="ts" generics="T">
|
|
15
|
+
import type { Snippet } from 'svelte';
|
|
16
|
+
import { scaleBand, scaleLinear } from 'd3-scale';
|
|
17
|
+
import { max, min } from 'd3-array';
|
|
18
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
|
|
19
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
20
|
+
import { Plot, Svg, estimateTextWidth, type PlotContext } from '../core/index.js';
|
|
21
|
+
import { AxisX, GridX, Legend } from '../guides/index.js';
|
|
22
|
+
import { PointerArea } from '../interactive/index.js';
|
|
23
|
+
import { percentileRank, type PercentileRank } from '../transforms/index.js';
|
|
24
|
+
import { createLocale, type LocaleCode } from '../locale/index.js';
|
|
25
|
+
import { base, type Medium, type Theme } from '../styles/index.js';
|
|
26
|
+
|
|
27
|
+
type Maybe = number | null | undefined;
|
|
28
|
+
|
|
29
|
+
interface Props {
|
|
30
|
+
/** One row per group (an occupation, a region, …). */
|
|
31
|
+
data: T[];
|
|
32
|
+
/** Group name, written above its strip. */
|
|
33
|
+
label: (d: T) => string;
|
|
34
|
+
/** The group's published percentiles: `p` from 0 to 100 (50 is the median). Missing values are skipped. */
|
|
35
|
+
percentiles: (d: T) => { p: number; value: Maybe }[];
|
|
36
|
+
/** The reader's value. Bindable; defaults to the median of the first highlighted group (or the first group). */
|
|
37
|
+
value?: number;
|
|
38
|
+
/** Groups to emphasise: highlight colour, bold name, and the group `summary` describes. */
|
|
39
|
+
highlight?: (d: T) => boolean;
|
|
40
|
+
/** Label of the number box (e.g. "Your salary"). Also its accessible name. */
|
|
41
|
+
inputLabel?: string;
|
|
42
|
+
/** Text before and after the number box (e.g. "£", "a year"). */
|
|
43
|
+
inputPrefix?: string;
|
|
44
|
+
inputSuffix?: string;
|
|
45
|
+
/** Slider step and rounding for clicks on the plot; defaults to a round step of about 1% of the range. */
|
|
46
|
+
step?: number;
|
|
47
|
+
/** Slider range; defaults to the x domain. */
|
|
48
|
+
min?: number;
|
|
49
|
+
max?: number;
|
|
50
|
+
/** Label of the "you" line. Defaults to the formatted value; a function gets the formatted value. */
|
|
51
|
+
youLabel?: string | ((formatted: string) => string);
|
|
52
|
+
/** Heading over the right-hand column of percentiles (e.g. "You earn more than"). */
|
|
53
|
+
readoutLabel?: string;
|
|
54
|
+
/** Text in the right-hand column; defaults to "65%", "<10%" or ">90%". */
|
|
55
|
+
readout?: (rank: PercentileRank, d: T) => string;
|
|
56
|
+
/** A sentence under the controls about the first highlighted group (e.g. "You earn more than 65% of housing officers"). Announced to screen readers as it changes. */
|
|
57
|
+
summary?: (rank: PercentileRank, d: T, value: number) => string;
|
|
58
|
+
/** Legend names for the median dot, the middle half (p25–p75) and the full published range. A legend is shown only for the names given. */
|
|
59
|
+
medianLabel?: string;
|
|
60
|
+
middleLabel?: string;
|
|
61
|
+
rangeLabel?: string;
|
|
62
|
+
/** Name of a percentile in dot tooltips; defaults to "P25". */
|
|
63
|
+
percentileLabel?: (p: number) => string;
|
|
64
|
+
style?: Theme;
|
|
65
|
+
locale?: LocaleCode;
|
|
66
|
+
medium?: Medium;
|
|
67
|
+
width?: number;
|
|
68
|
+
title?: string;
|
|
69
|
+
subtitle?: string;
|
|
70
|
+
notes?: string;
|
|
71
|
+
source?: string;
|
|
72
|
+
alt?: string;
|
|
73
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
74
|
+
embed?: ChartEmbed;
|
|
75
|
+
/** Value format (labels, tooltips); defaults to locale numbers. */
|
|
76
|
+
format?: (n: number) => string;
|
|
77
|
+
/** Axis tick format; defaults to `format`. */
|
|
78
|
+
tickFormat?: (n: number) => string;
|
|
79
|
+
/** Strip colour; defaults to the highlight colour for highlighted groups and the neutral grey for the rest. */
|
|
80
|
+
color?: (d: T) => string;
|
|
81
|
+
/** x domain; defaults to the lowest and highest published values, rounded. */
|
|
82
|
+
domain?: [number, number];
|
|
83
|
+
/** Height of each row (name and strip), px. */
|
|
84
|
+
rowHeight?: number;
|
|
85
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
86
|
+
annotations?: Snippet<[PlotContext]>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let {
|
|
90
|
+
data,
|
|
91
|
+
label,
|
|
92
|
+
percentiles,
|
|
93
|
+
value = $bindable(),
|
|
94
|
+
highlight,
|
|
95
|
+
inputLabel,
|
|
96
|
+
inputPrefix,
|
|
97
|
+
inputSuffix,
|
|
98
|
+
step,
|
|
99
|
+
min: minValue,
|
|
100
|
+
max: maxValue,
|
|
101
|
+
youLabel,
|
|
102
|
+
readoutLabel,
|
|
103
|
+
readout,
|
|
104
|
+
summary,
|
|
105
|
+
medianLabel,
|
|
106
|
+
middleLabel,
|
|
107
|
+
rangeLabel,
|
|
108
|
+
percentileLabel = (p: number) => `P${p}`,
|
|
109
|
+
style = base,
|
|
110
|
+
locale,
|
|
111
|
+
medium = 'web',
|
|
112
|
+
width,
|
|
113
|
+
title,
|
|
114
|
+
subtitle,
|
|
115
|
+
notes,
|
|
116
|
+
source,
|
|
117
|
+
alt,
|
|
118
|
+
embed,
|
|
119
|
+
format,
|
|
120
|
+
tickFormat,
|
|
121
|
+
color,
|
|
122
|
+
domain,
|
|
123
|
+
rowHeight = 52,
|
|
124
|
+
annotations
|
|
125
|
+
}: Props = $props();
|
|
126
|
+
|
|
127
|
+
const has = (v: Maybe): v is number => v !== null && v !== undefined && Number.isFinite(v);
|
|
128
|
+
const theme = $derived(style);
|
|
129
|
+
const numbers = $derived(createLocale(locale ?? theme.defaultLocale));
|
|
130
|
+
const fmt = $derived(format ?? numbers.number);
|
|
131
|
+
const fontSize = $derived(theme.plot.fontSize);
|
|
132
|
+
const uid = $props.id();
|
|
133
|
+
|
|
134
|
+
/** Each group with its usable points, sorted by percentile. */
|
|
135
|
+
const groups = $derived(
|
|
136
|
+
data.map((d) => {
|
|
137
|
+
const points = percentiles(d)
|
|
138
|
+
.filter((q): q is { p: number; value: number } => has(q.value))
|
|
139
|
+
.toSorted((a, b) => a.p - b.p);
|
|
140
|
+
const at = (p: number) => points.find((q) => q.p === p)?.value;
|
|
141
|
+
return { d, name: label(d), points, median: at(50), q1: at(25), q3: at(75), on: highlight?.(d) ?? false };
|
|
142
|
+
})
|
|
143
|
+
);
|
|
144
|
+
const values = $derived(groups.flatMap((g) => g.points.map((q) => q.value)));
|
|
145
|
+
const x = $derived(
|
|
146
|
+
scaleLinear()
|
|
147
|
+
.domain(domain ?? [min(values) ?? 0, max(values) ?? 1])
|
|
148
|
+
.nice()
|
|
149
|
+
);
|
|
150
|
+
const lo = $derived(minValue ?? x.domain()[0]);
|
|
151
|
+
const hi = $derived(maxValue ?? x.domain()[1]);
|
|
152
|
+
const roundStep = $derived(step ?? 10 ** Math.floor(Math.log10(Math.max(hi - lo, 1e-9) / 100)));
|
|
153
|
+
|
|
154
|
+
const primary = $derived(groups.find((g) => g.on) ?? groups[0]);
|
|
155
|
+
const fallback = $derived(primary?.median ?? primary?.points[Math.floor(primary.points.length / 2)]?.value ?? lo);
|
|
156
|
+
const current = $derived(has(value) ? value : fallback);
|
|
157
|
+
const clamp = (v: number) => Math.min(hi, Math.max(lo, v));
|
|
158
|
+
function set(v: number) {
|
|
159
|
+
if (Number.isFinite(v)) value = v;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ranks = $derived(groups.map((g) => percentileRank(current, g.points)));
|
|
163
|
+
const percent = $derived(numbers.format('.0f'));
|
|
164
|
+
const readoutText = (rank: PercentileRank | undefined, d: T) => {
|
|
165
|
+
if (!rank) return '–';
|
|
166
|
+
if (readout) return readout(rank, d);
|
|
167
|
+
const n = percent(rank.percentile);
|
|
168
|
+
return rank.below ? `<${n}%` : rank.above ? `>${n}%` : `${n}%`;
|
|
169
|
+
};
|
|
170
|
+
const readouts = $derived(groups.map((g, i) => readoutText(ranks[i], g.d)));
|
|
171
|
+
const summaryText = $derived.by(() => {
|
|
172
|
+
if (!summary || !primary) return '';
|
|
173
|
+
const rank = ranks[groups.indexOf(primary)];
|
|
174
|
+
return rank ? summary(rank, primary.d, current) : '';
|
|
175
|
+
});
|
|
176
|
+
const you = $derived(typeof youLabel === 'function' ? youLabel(fmt(current)) : (youLabel ?? fmt(current)));
|
|
177
|
+
|
|
178
|
+
const stripColor = $derived(
|
|
179
|
+
(g: (typeof groups)[number]) =>
|
|
180
|
+
color?.(g.d) ?? (g.on ? theme.palettes.semantic.highlight : theme.palettes.semantic.neutral)
|
|
181
|
+
);
|
|
182
|
+
const legendColor = $derived(primary ? stripColor(primary) : theme.palettes.semantic.highlight);
|
|
183
|
+
|
|
184
|
+
/** The right-hand column fits the readouts; its heading wraps to the column, above the plot. */
|
|
185
|
+
const headingSize = $derived(fontSize * 0.9);
|
|
186
|
+
const column = $derived(
|
|
187
|
+
Math.max(
|
|
188
|
+
...readouts.map((t) => estimateTextWidth(t, fontSize)),
|
|
189
|
+
...(readoutLabel ?? '').split(/\s+/).map((w) => estimateTextWidth(w, headingSize)),
|
|
190
|
+
readoutLabel ? Math.min(estimateTextWidth(readoutLabel, headingSize), 64) : 0,
|
|
191
|
+
0
|
|
192
|
+
)
|
|
193
|
+
);
|
|
194
|
+
const right = $derived(column + 14);
|
|
195
|
+
const headingLines = $derived.by(() => {
|
|
196
|
+
const lines: string[] = [];
|
|
197
|
+
for (const word of (readoutLabel ?? '').split(/\s+/).filter(Boolean)) {
|
|
198
|
+
const last = lines.at(-1);
|
|
199
|
+
if (last !== undefined && estimateTextWidth(`${last} ${word}`, headingSize) <= column)
|
|
200
|
+
lines[lines.length - 1] = `${last} ${word}`;
|
|
201
|
+
else lines.push(word);
|
|
202
|
+
}
|
|
203
|
+
return lines;
|
|
204
|
+
});
|
|
205
|
+
const lineHeight = $derived(Math.round(headingSize * 1.2));
|
|
206
|
+
const top = $derived(20 + Math.max(0, headingLines.length - 1) * lineHeight);
|
|
207
|
+
const y = $derived(scaleBand<string>().domain(groups.map((g) => g.name)));
|
|
208
|
+
/** Baselines inside a row: the name, then the strip under it. */
|
|
209
|
+
const nameY = $derived(fontSize + 2);
|
|
210
|
+
const stripY = $derived(Math.max(nameY + 18, rowHeight * 0.66));
|
|
211
|
+
|
|
212
|
+
function fromPointer(plot: PlotContext, px: number, event: PointerEvent) {
|
|
213
|
+
if (event.type !== 'pointerdown' && event.buttons === 0) return;
|
|
214
|
+
const raw = plot.x.invert?.(px);
|
|
215
|
+
if (typeof raw === 'number') set(clamp(Math.round(raw / roundStep) * roundStep));
|
|
216
|
+
}
|
|
217
|
+
</script>
|
|
218
|
+
|
|
219
|
+
<Chart {style} {locale} {medium} {width} {alt} {embed}>
|
|
220
|
+
<Header>
|
|
221
|
+
{#if title}<Title>{title}</Title>{/if}
|
|
222
|
+
{#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
|
|
223
|
+
{#if medium !== 'print'}
|
|
224
|
+
<div class="mz-percentile-controls">
|
|
225
|
+
<label class="mz-percentile-input" for="{uid}-value">
|
|
226
|
+
{#if inputLabel}<span class="mz-percentile-input-label">{inputLabel}</span>{/if}
|
|
227
|
+
<span class="mz-percentile-field">
|
|
228
|
+
{#if inputPrefix}<span aria-hidden="true">{inputPrefix}</span>{/if}
|
|
229
|
+
<input
|
|
230
|
+
id="{uid}-value"
|
|
231
|
+
type="number"
|
|
232
|
+
inputmode="decimal"
|
|
233
|
+
min={lo}
|
|
234
|
+
max={hi}
|
|
235
|
+
step="any"
|
|
236
|
+
value={current}
|
|
237
|
+
aria-label={inputLabel ? undefined : you}
|
|
238
|
+
oninput={(e) => set(e.currentTarget.valueAsNumber)}
|
|
239
|
+
/>
|
|
240
|
+
{#if inputSuffix}<span aria-hidden="true">{inputSuffix}</span>{/if}
|
|
241
|
+
</span>
|
|
242
|
+
</label>
|
|
243
|
+
<input
|
|
244
|
+
class="mz-percentile-slider"
|
|
245
|
+
type="range"
|
|
246
|
+
min={lo}
|
|
247
|
+
max={hi}
|
|
248
|
+
step={roundStep}
|
|
249
|
+
value={clamp(current)}
|
|
250
|
+
aria-label={inputLabel ?? you}
|
|
251
|
+
aria-valuetext={fmt(current)}
|
|
252
|
+
oninput={(e) => set(e.currentTarget.valueAsNumber)}
|
|
253
|
+
/>
|
|
254
|
+
</div>
|
|
255
|
+
{/if}
|
|
256
|
+
{#if summaryText}<p class="mz-percentile-summary" aria-live="polite">{summaryText}</p>{/if}
|
|
257
|
+
{#if medianLabel || middleLabel || rangeLabel}
|
|
258
|
+
<div class="mz-percentile-legend">
|
|
259
|
+
{#if medianLabel}<Legend shape="circle" items={[{ label: medianLabel, color: legendColor }]} />{/if}
|
|
260
|
+
{#if middleLabel}<Legend items={[{ label: middleLabel, color: legendColor }]} />{/if}
|
|
261
|
+
{#if rangeLabel}<Legend shape="line" items={[{ label: rangeLabel, color: legendColor }]} />{/if}
|
|
262
|
+
</div>
|
|
263
|
+
{/if}
|
|
264
|
+
</Header>
|
|
265
|
+
|
|
266
|
+
<Plot {x} {y} height={groups.length * rowHeight} padding={{ left: 4, right, top, bottom: 24 }}>
|
|
267
|
+
{#snippet children(plot)}
|
|
268
|
+
{@const yx = clamp(current)}
|
|
269
|
+
{@const px = plot.x(Math.min(x.domain()[1], Math.max(x.domain()[0], yx))) ?? 0}
|
|
270
|
+
{@const anchor = px > plot.width * 0.8 ? 'end' : px < plot.width * 0.2 ? 'start' : 'middle'}
|
|
271
|
+
<Svg>
|
|
272
|
+
<GridX ticks={4} />
|
|
273
|
+
<AxisX ticks={4} format={tickFormat ?? fmt} />
|
|
274
|
+
<PointerArea onmove={({ x: p, event }) => fromPointer(plot, p, event)} />
|
|
275
|
+
<!-- Above the plot, in the right-hand column (clear of the "you" label, which stays over the plot area). -->
|
|
276
|
+
{#each headingLines as line, i (i)}
|
|
277
|
+
<text
|
|
278
|
+
class="mz-percentile-heading"
|
|
279
|
+
x={plot.width + right}
|
|
280
|
+
y={-8 - (headingLines.length - 1 - i) * lineHeight}
|
|
281
|
+
text-anchor="end">{line}</text
|
|
282
|
+
>
|
|
283
|
+
{/each}
|
|
284
|
+
<!-- Under the rows, so group names (with a background halo) and dots sit on top of it. -->
|
|
285
|
+
<line class="mz-percentile-you" x1={px} x2={px} y1={-4} y2={plot.height} />
|
|
286
|
+
{#each groups as g, i (g.name)}
|
|
287
|
+
{@const rowTop = plot.y(g.name) ?? 0}
|
|
288
|
+
{@const c = stripColor(g)}
|
|
289
|
+
{@const first = g.points[0]}
|
|
290
|
+
{@const last = g.points[g.points.length - 1]}
|
|
291
|
+
<g class="mz-percentile-row" class:on={g.on} transform="translate(0,{rowTop})">
|
|
292
|
+
<text class="mz-percentile-name" y={nameY}>{g.name}</text>
|
|
293
|
+
{#if first && last}
|
|
294
|
+
<line
|
|
295
|
+
x1={plot.x(first.value)}
|
|
296
|
+
x2={plot.x(last.value)}
|
|
297
|
+
y1={stripY}
|
|
298
|
+
y2={stripY}
|
|
299
|
+
stroke={c}
|
|
300
|
+
stroke-width="2"
|
|
301
|
+
stroke-opacity="0.5"
|
|
302
|
+
/>
|
|
303
|
+
{/if}
|
|
304
|
+
{#if has(g.q1) && has(g.q3)}
|
|
305
|
+
<line
|
|
306
|
+
x1={plot.x(g.q1)}
|
|
307
|
+
x2={plot.x(g.q3)}
|
|
308
|
+
y1={stripY}
|
|
309
|
+
y2={stripY}
|
|
310
|
+
stroke={c}
|
|
311
|
+
stroke-width="10"
|
|
312
|
+
stroke-opacity="0.35"
|
|
313
|
+
/>
|
|
314
|
+
{/if}
|
|
315
|
+
{#each g.points.filter((q) => q.p !== 50) as q (q.p)}
|
|
316
|
+
<circle cx={plot.x(q.value)} cy={stripY} r="3" fill={c}>
|
|
317
|
+
<title>{g.name}, {percentileLabel(q.p)}: {fmt(q.value)}</title>
|
|
318
|
+
</circle>
|
|
319
|
+
{/each}
|
|
320
|
+
{#if has(g.median)}
|
|
321
|
+
<circle
|
|
322
|
+
cx={plot.x(g.median)}
|
|
323
|
+
cy={stripY}
|
|
324
|
+
r="6.5"
|
|
325
|
+
fill={c}
|
|
326
|
+
stroke={theme.tokens['--mz-color-bg']}
|
|
327
|
+
stroke-width="1.5"
|
|
328
|
+
>
|
|
329
|
+
<title>{g.name}, {medianLabel ?? percentileLabel(50)}: {fmt(g.median)}</title>
|
|
330
|
+
</circle>
|
|
331
|
+
{/if}
|
|
332
|
+
<text class="mz-percentile-readout" x={plot.width + right} y={stripY} dy="0.35em" text-anchor="end"
|
|
333
|
+
>{readouts[i]}</text
|
|
334
|
+
>
|
|
335
|
+
</g>
|
|
336
|
+
{/each}
|
|
337
|
+
<text class="mz-percentile-you-label" x={px} y={-8} text-anchor={anchor}>{you}</text>
|
|
338
|
+
{@render annotations?.(plot)}
|
|
339
|
+
</Svg>
|
|
340
|
+
{/snippet}
|
|
341
|
+
</Plot>
|
|
342
|
+
|
|
343
|
+
{#if notes || source}
|
|
344
|
+
<Footer>
|
|
345
|
+
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
346
|
+
{#if source}<Source>{source}</Source>{/if}
|
|
347
|
+
</Footer>
|
|
348
|
+
{/if}
|
|
349
|
+
</Chart>
|
|
350
|
+
|
|
351
|
+
<style>
|
|
352
|
+
.mz-percentile-controls {
|
|
353
|
+
display: flex;
|
|
354
|
+
flex-wrap: wrap;
|
|
355
|
+
align-items: center;
|
|
356
|
+
gap: 0.5rem 1rem;
|
|
357
|
+
font-family: var(--mz-font-label);
|
|
358
|
+
font-size: var(--mz-size-small);
|
|
359
|
+
}
|
|
360
|
+
.mz-percentile-input {
|
|
361
|
+
display: inline-flex;
|
|
362
|
+
align-items: center;
|
|
363
|
+
gap: 0.5rem;
|
|
364
|
+
color: var(--mz-color-text);
|
|
365
|
+
}
|
|
366
|
+
.mz-percentile-input-label {
|
|
367
|
+
font-weight: var(--mz-weight-label);
|
|
368
|
+
text-transform: var(--mz-label-transform);
|
|
369
|
+
letter-spacing: var(--mz-label-tracking);
|
|
370
|
+
}
|
|
371
|
+
.mz-percentile-field {
|
|
372
|
+
display: inline-flex;
|
|
373
|
+
align-items: center;
|
|
374
|
+
gap: 0.25rem;
|
|
375
|
+
padding: 0.2rem 0.5rem;
|
|
376
|
+
border: 1px solid var(--mz-color-axis);
|
|
377
|
+
border-radius: var(--mz-radius);
|
|
378
|
+
background: var(--mz-color-bg);
|
|
379
|
+
}
|
|
380
|
+
.mz-percentile-field:focus-within {
|
|
381
|
+
outline: 2px solid var(--mz-color-accent);
|
|
382
|
+
outline-offset: 1px;
|
|
383
|
+
}
|
|
384
|
+
.mz-percentile-field input {
|
|
385
|
+
width: 7ch;
|
|
386
|
+
border: 0;
|
|
387
|
+
padding: 0;
|
|
388
|
+
background: transparent;
|
|
389
|
+
color: var(--mz-color-text);
|
|
390
|
+
font: inherit;
|
|
391
|
+
font-size: var(--mz-size-body);
|
|
392
|
+
font-weight: var(--mz-weight-strong);
|
|
393
|
+
font-variant-numeric: tabular-nums;
|
|
394
|
+
outline: none;
|
|
395
|
+
appearance: textfield;
|
|
396
|
+
-moz-appearance: textfield;
|
|
397
|
+
}
|
|
398
|
+
.mz-percentile-field input::-webkit-inner-spin-button,
|
|
399
|
+
.mz-percentile-field input::-webkit-outer-spin-button {
|
|
400
|
+
-webkit-appearance: none;
|
|
401
|
+
margin: 0;
|
|
402
|
+
}
|
|
403
|
+
.mz-percentile-slider {
|
|
404
|
+
flex: 1 1 10rem;
|
|
405
|
+
min-width: 8rem;
|
|
406
|
+
max-width: 22rem;
|
|
407
|
+
accent-color: var(--mz-color-accent);
|
|
408
|
+
}
|
|
409
|
+
.mz-percentile-summary {
|
|
410
|
+
margin: 0;
|
|
411
|
+
font-family: var(--mz-font-body);
|
|
412
|
+
font-size: var(--mz-size-body);
|
|
413
|
+
color: var(--mz-color-text);
|
|
414
|
+
}
|
|
415
|
+
.mz-percentile-legend {
|
|
416
|
+
display: flex;
|
|
417
|
+
flex-wrap: wrap;
|
|
418
|
+
gap: 0 1rem;
|
|
419
|
+
}
|
|
420
|
+
.mz-percentile-name,
|
|
421
|
+
.mz-percentile-readout,
|
|
422
|
+
.mz-percentile-heading,
|
|
423
|
+
.mz-percentile-you-label {
|
|
424
|
+
font-family: var(--mz-font-body);
|
|
425
|
+
font-size: var(--mz-size-axis);
|
|
426
|
+
fill: var(--mz-color-text);
|
|
427
|
+
}
|
|
428
|
+
.on .mz-percentile-name,
|
|
429
|
+
.mz-percentile-readout,
|
|
430
|
+
.mz-percentile-you-label {
|
|
431
|
+
font-weight: var(--mz-weight-strong);
|
|
432
|
+
}
|
|
433
|
+
/* A background-coloured outline keeps names legible where the "you" line crosses them. */
|
|
434
|
+
.mz-percentile-name {
|
|
435
|
+
paint-order: stroke;
|
|
436
|
+
stroke: var(--mz-color-bg);
|
|
437
|
+
stroke-width: 4px;
|
|
438
|
+
stroke-linejoin: round;
|
|
439
|
+
}
|
|
440
|
+
.mz-percentile-readout {
|
|
441
|
+
font-variant-numeric: tabular-nums;
|
|
442
|
+
}
|
|
443
|
+
.mz-percentile-heading {
|
|
444
|
+
fill: var(--mz-color-muted);
|
|
445
|
+
font-size: calc(var(--mz-size-axis) * 0.9);
|
|
446
|
+
}
|
|
447
|
+
.mz-percentile-you {
|
|
448
|
+
stroke: var(--mz-color-text);
|
|
449
|
+
stroke-width: 1.5;
|
|
450
|
+
pointer-events: none;
|
|
451
|
+
}
|
|
452
|
+
</style>
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
2
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
3
|
+
import { type PlotContext } from '../core/index.js';
|
|
4
|
+
import { type PercentileRank } from '../transforms/index.js';
|
|
5
|
+
import { type LocaleCode } from '../locale/index.js';
|
|
6
|
+
import { type Medium, type Theme } from '../styles/index.js';
|
|
7
|
+
declare function $$render<T>(): {
|
|
8
|
+
props: {
|
|
9
|
+
/** One row per group (an occupation, a region, …). */
|
|
10
|
+
data: T[];
|
|
11
|
+
/** Group name, written above its strip. */
|
|
12
|
+
label: (d: T) => string;
|
|
13
|
+
/** The group's published percentiles: `p` from 0 to 100 (50 is the median). Missing values are skipped. */
|
|
14
|
+
percentiles: (d: T) => {
|
|
15
|
+
p: number;
|
|
16
|
+
value: number | null | undefined;
|
|
17
|
+
}[];
|
|
18
|
+
/** The reader's value. Bindable; defaults to the median of the first highlighted group (or the first group). */
|
|
19
|
+
value?: number;
|
|
20
|
+
/** Groups to emphasise: highlight colour, bold name, and the group `summary` describes. */
|
|
21
|
+
highlight?: (d: T) => boolean;
|
|
22
|
+
/** Label of the number box (e.g. "Your salary"). Also its accessible name. */
|
|
23
|
+
inputLabel?: string;
|
|
24
|
+
/** Text before and after the number box (e.g. "£", "a year"). */
|
|
25
|
+
inputPrefix?: string;
|
|
26
|
+
inputSuffix?: string;
|
|
27
|
+
/** Slider step and rounding for clicks on the plot; defaults to a round step of about 1% of the range. */
|
|
28
|
+
step?: number;
|
|
29
|
+
/** Slider range; defaults to the x domain. */
|
|
30
|
+
min?: number;
|
|
31
|
+
max?: number;
|
|
32
|
+
/** Label of the "you" line. Defaults to the formatted value; a function gets the formatted value. */
|
|
33
|
+
youLabel?: string | ((formatted: string) => string);
|
|
34
|
+
/** Heading over the right-hand column of percentiles (e.g. "You earn more than"). */
|
|
35
|
+
readoutLabel?: string;
|
|
36
|
+
/** Text in the right-hand column; defaults to "65%", "<10%" or ">90%". */
|
|
37
|
+
readout?: (rank: PercentileRank, d: T) => string;
|
|
38
|
+
/** A sentence under the controls about the first highlighted group (e.g. "You earn more than 65% of housing officers"). Announced to screen readers as it changes. */
|
|
39
|
+
summary?: (rank: PercentileRank, d: T, value: number) => string;
|
|
40
|
+
/** Legend names for the median dot, the middle half (p25–p75) and the full published range. A legend is shown only for the names given. */
|
|
41
|
+
medianLabel?: string;
|
|
42
|
+
middleLabel?: string;
|
|
43
|
+
rangeLabel?: string;
|
|
44
|
+
/** Name of a percentile in dot tooltips; defaults to "P25". */
|
|
45
|
+
percentileLabel?: (p: number) => string;
|
|
46
|
+
style?: Theme;
|
|
47
|
+
locale?: LocaleCode;
|
|
48
|
+
medium?: Medium;
|
|
49
|
+
width?: number;
|
|
50
|
+
title?: string;
|
|
51
|
+
subtitle?: string;
|
|
52
|
+
notes?: string;
|
|
53
|
+
source?: string;
|
|
54
|
+
alt?: string;
|
|
55
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
56
|
+
embed?: ChartEmbed;
|
|
57
|
+
/** Value format (labels, tooltips); defaults to locale numbers. */
|
|
58
|
+
format?: (n: number) => string;
|
|
59
|
+
/** Axis tick format; defaults to `format`. */
|
|
60
|
+
tickFormat?: (n: number) => string;
|
|
61
|
+
/** Strip colour; defaults to the highlight colour for highlighted groups and the neutral grey for the rest. */
|
|
62
|
+
color?: (d: T) => string;
|
|
63
|
+
/** x domain; defaults to the lowest and highest published values, rounded. */
|
|
64
|
+
domain?: [number, number];
|
|
65
|
+
/** Height of each row (name and strip), px. */
|
|
66
|
+
rowHeight?: number;
|
|
67
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
68
|
+
annotations?: Snippet<[PlotContext]>;
|
|
69
|
+
};
|
|
70
|
+
exports: {};
|
|
71
|
+
bindings: "value";
|
|
72
|
+
slots: {};
|
|
73
|
+
events: {};
|
|
74
|
+
};
|
|
75
|
+
declare class __sveltets_Render<T> {
|
|
76
|
+
props(): ReturnType<typeof $$render<T>>['props'];
|
|
77
|
+
events(): ReturnType<typeof $$render<T>>['events'];
|
|
78
|
+
slots(): ReturnType<typeof $$render<T>>['slots'];
|
|
79
|
+
bindings(): "value";
|
|
80
|
+
exports(): {};
|
|
81
|
+
}
|
|
82
|
+
interface $$IsomorphicComponent {
|
|
83
|
+
new <T>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<T>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<T>['props']>, ReturnType<__sveltets_Render<T>['events']>, ReturnType<__sveltets_Render<T>['slots']>> & {
|
|
84
|
+
$$bindings?: ReturnType<__sveltets_Render<T>['bindings']>;
|
|
85
|
+
} & ReturnType<__sveltets_Render<T>['exports']>;
|
|
86
|
+
<T>(internal: unknown, props: ReturnType<__sveltets_Render<T>['props']> & {}): ReturnType<__sveltets_Render<T>['exports']>;
|
|
87
|
+
z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Recipe: "how do you compare?". One strip per group showing its published
|
|
91
|
+
* percentiles (a line across the range, a thicker band for the middle half, a
|
|
92
|
+
* dot per percentile and a large dot for the median), a "you" line at the
|
|
93
|
+
* reader's value, and the reader's estimated percentile in each group at the
|
|
94
|
+
* right. Readers set the value with a number box, a slider, or by clicking or
|
|
95
|
+
* dragging on the strips. Percentiles are interpolated linearly between the
|
|
96
|
+
* published points (see `percentileRank` in `@samizdata/mozaic/transforms`).
|
|
97
|
+
* In print the controls are hidden and the chart shows the starting value.
|
|
98
|
+
* Use it as is, or run `mozaic eject PercentileChart` to copy this file into
|
|
99
|
+
* your project and change anything.
|
|
100
|
+
*/
|
|
101
|
+
declare const PercentileChart: $$IsomorphicComponent;
|
|
102
|
+
type PercentileChart<T> = InstanceType<typeof PercentileChart<T>>;
|
|
103
|
+
export default PercentileChart;
|
package/dist/recipes/index.d.ts
CHANGED
|
@@ -6,5 +6,6 @@ export { default as ArrowChart } from './ArrowChart.svelte';
|
|
|
6
6
|
export { default as BarDotChart } from './BarDotChart.svelte';
|
|
7
7
|
export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
|
+
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
9
10
|
/** Recipe names accepted by `mozaic eject`. */
|
|
10
|
-
export declare const recipes: readonly ["BarChart", "ColumnChart", "LineChart", "ScatterChart", "ArrowChart", "BarDotChart", "StackedBarChart", "MosaicChart"];
|
|
11
|
+
export declare const recipes: readonly ["BarChart", "ColumnChart", "LineChart", "ScatterChart", "ArrowChart", "BarDotChart", "StackedBarChart", "MosaicChart", "PercentileChart"];
|
package/dist/recipes/index.js
CHANGED
|
@@ -6,6 +6,7 @@ export { default as ArrowChart } from './ArrowChart.svelte';
|
|
|
6
6
|
export { default as BarDotChart } from './BarDotChart.svelte';
|
|
7
7
|
export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
|
+
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
9
10
|
/** Recipe names accepted by `mozaic eject`. */
|
|
10
11
|
export const recipes = [
|
|
11
12
|
'BarChart',
|
|
@@ -15,5 +16,6 @@ export const recipes = [
|
|
|
15
16
|
'ArrowChart',
|
|
16
17
|
'BarDotChart',
|
|
17
18
|
'StackedBarChart',
|
|
18
|
-
'MosaicChart'
|
|
19
|
+
'MosaicChart',
|
|
20
|
+
'PercentileChart'
|
|
19
21
|
];
|
|
@@ -6,3 +6,4 @@ export { dodge } from './dodge.js';
|
|
|
6
6
|
export { treemapLayout, type TreemapCell } from './treemap.js';
|
|
7
7
|
export { hemicycleLayout, type HemicycleLayout, type HemicycleOptions, type Seat } from './hemicycle.js';
|
|
8
8
|
export { kernelSmooth, loess, type Kernel, type KernelSmoothOptions, type LoessOptions, type Smoothed } from './smooth.js';
|
|
9
|
+
export { percentileRank, type PercentilePoint, type PercentileRank } from './percentile.js';
|
package/dist/transforms/index.js
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** One published point of a distribution: the value below which `p`% of the group falls. */
|
|
2
|
+
export interface PercentilePoint {
|
|
3
|
+
/** Percentile, 0–100 (50 is the median). */
|
|
4
|
+
p: number;
|
|
5
|
+
value: number;
|
|
6
|
+
}
|
|
7
|
+
/** Where a value sits in a distribution, from {@link percentileRank}. */
|
|
8
|
+
export interface PercentileRank {
|
|
9
|
+
/** Estimated percentile, 0–100. Outside the published range, the nearest published percentile. */
|
|
10
|
+
percentile: number;
|
|
11
|
+
/** The value is below the lowest published point, so the true percentile is lower than `percentile`. */
|
|
12
|
+
below: boolean;
|
|
13
|
+
/** The value is above the highest published point, so the true percentile is higher than `percentile`. */
|
|
14
|
+
above: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Estimate the percentile of `value` in a distribution known only at some
|
|
18
|
+
* percentiles (as statistics offices publish pay: 10th, 25th, median, …), by
|
|
19
|
+
* linear interpolation between the neighbouring points. Points with a missing
|
|
20
|
+
* or non-finite value are skipped. Returns `undefined` when no point is left.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* percentileRank(38000, [{ p: 25, value: 29951 }, { p: 50, value: 34432 }, { p: 75, value: 40009 }]);
|
|
24
|
+
* // { percentile: 67.8…, below: false, above: false }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function percentileRank(value: number, points: {
|
|
28
|
+
p: number;
|
|
29
|
+
value: number | null | undefined;
|
|
30
|
+
}[]): PercentileRank | undefined;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimate the percentile of `value` in a distribution known only at some
|
|
3
|
+
* percentiles (as statistics offices publish pay: 10th, 25th, median, …), by
|
|
4
|
+
* linear interpolation between the neighbouring points. Points with a missing
|
|
5
|
+
* or non-finite value are skipped. Returns `undefined` when no point is left.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* percentileRank(38000, [{ p: 25, value: 29951 }, { p: 50, value: 34432 }, { p: 75, value: 40009 }]);
|
|
9
|
+
* // { percentile: 67.8…, below: false, above: false }
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export function percentileRank(value, points) {
|
|
13
|
+
const known = points
|
|
14
|
+
.filter((d) => d.value !== null && d.value !== undefined && Number.isFinite(d.value))
|
|
15
|
+
.toSorted((a, b) => a.p - b.p);
|
|
16
|
+
if (!known.length || !Number.isFinite(value))
|
|
17
|
+
return undefined;
|
|
18
|
+
const first = known[0];
|
|
19
|
+
const last = known[known.length - 1];
|
|
20
|
+
if (value < first.value)
|
|
21
|
+
return { percentile: first.p, below: true, above: false };
|
|
22
|
+
if (value > last.value)
|
|
23
|
+
return { percentile: last.p, below: false, above: true };
|
|
24
|
+
// The last point at or below the value; the next one is above it (or there is none).
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i + 1 < known.length && known[i + 1].value <= value)
|
|
27
|
+
i++;
|
|
28
|
+
const a = known[i];
|
|
29
|
+
const b = known[i + 1];
|
|
30
|
+
if (!b)
|
|
31
|
+
return { percentile: a.p, below: false, above: false };
|
|
32
|
+
const t = (value - a.value) / (b.value - a.value);
|
|
33
|
+
return { percentile: a.p + t * (b.p - a.p), below: false, above: false };
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Recipe: "how do you compare?". One strip per group showing its published
|
|
4
|
+
percentiles (a line across the range, a thicker band for the middle half, a
|
|
5
|
+
dot per percentile and a large dot for the median), a "you" line at the
|
|
6
|
+
reader's value, and the reader's estimated percentile in each group at the
|
|
7
|
+
right. Readers set the value with a number box, a slider, or by clicking or
|
|
8
|
+
dragging on the strips. Percentiles are interpolated linearly between the
|
|
9
|
+
published points (see `percentileRank` in `@samizdata/mozaic/transforms`).
|
|
10
|
+
In print the controls are hidden and the chart shows the starting value.
|
|
11
|
+
Use it as is, or run `mozaic eject PercentileChart` to copy this file into
|
|
12
|
+
your project and change anything.
|
|
13
|
+
-->
|
|
14
|
+
<script lang="ts" generics="T">
|
|
15
|
+
import type { Snippet } from 'svelte';
|
|
16
|
+
import { scaleBand, scaleLinear } from 'd3-scale';
|
|
17
|
+
import { max, min } from 'd3-array';
|
|
18
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
|
|
19
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
20
|
+
import { Plot, Svg, estimateTextWidth, type PlotContext } from '../core/index.js';
|
|
21
|
+
import { AxisX, GridX, Legend } from '../guides/index.js';
|
|
22
|
+
import { PointerArea } from '../interactive/index.js';
|
|
23
|
+
import { percentileRank, type PercentileRank } from '../transforms/index.js';
|
|
24
|
+
import { createLocale, type LocaleCode } from '../locale/index.js';
|
|
25
|
+
import { base, type Medium, type Theme } from '../styles/index.js';
|
|
26
|
+
|
|
27
|
+
type Maybe = number | null | undefined;
|
|
28
|
+
|
|
29
|
+
interface Props {
|
|
30
|
+
/** One row per group (an occupation, a region, …). */
|
|
31
|
+
data: T[];
|
|
32
|
+
/** Group name, written above its strip. */
|
|
33
|
+
label: (d: T) => string;
|
|
34
|
+
/** The group's published percentiles: `p` from 0 to 100 (50 is the median). Missing values are skipped. */
|
|
35
|
+
percentiles: (d: T) => { p: number; value: Maybe }[];
|
|
36
|
+
/** The reader's value. Bindable; defaults to the median of the first highlighted group (or the first group). */
|
|
37
|
+
value?: number;
|
|
38
|
+
/** Groups to emphasise: highlight colour, bold name, and the group `summary` describes. */
|
|
39
|
+
highlight?: (d: T) => boolean;
|
|
40
|
+
/** Label of the number box (e.g. "Your salary"). Also its accessible name. */
|
|
41
|
+
inputLabel?: string;
|
|
42
|
+
/** Text before and after the number box (e.g. "£", "a year"). */
|
|
43
|
+
inputPrefix?: string;
|
|
44
|
+
inputSuffix?: string;
|
|
45
|
+
/** Slider step and rounding for clicks on the plot; defaults to a round step of about 1% of the range. */
|
|
46
|
+
step?: number;
|
|
47
|
+
/** Slider range; defaults to the x domain. */
|
|
48
|
+
min?: number;
|
|
49
|
+
max?: number;
|
|
50
|
+
/** Label of the "you" line. Defaults to the formatted value; a function gets the formatted value. */
|
|
51
|
+
youLabel?: string | ((formatted: string) => string);
|
|
52
|
+
/** Heading over the right-hand column of percentiles (e.g. "You earn more than"). */
|
|
53
|
+
readoutLabel?: string;
|
|
54
|
+
/** Text in the right-hand column; defaults to "65%", "<10%" or ">90%". */
|
|
55
|
+
readout?: (rank: PercentileRank, d: T) => string;
|
|
56
|
+
/** A sentence under the controls about the first highlighted group (e.g. "You earn more than 65% of housing officers"). Announced to screen readers as it changes. */
|
|
57
|
+
summary?: (rank: PercentileRank, d: T, value: number) => string;
|
|
58
|
+
/** Legend names for the median dot, the middle half (p25–p75) and the full published range. A legend is shown only for the names given. */
|
|
59
|
+
medianLabel?: string;
|
|
60
|
+
middleLabel?: string;
|
|
61
|
+
rangeLabel?: string;
|
|
62
|
+
/** Name of a percentile in dot tooltips; defaults to "P25". */
|
|
63
|
+
percentileLabel?: (p: number) => string;
|
|
64
|
+
style?: Theme;
|
|
65
|
+
locale?: LocaleCode;
|
|
66
|
+
medium?: Medium;
|
|
67
|
+
width?: number;
|
|
68
|
+
title?: string;
|
|
69
|
+
subtitle?: string;
|
|
70
|
+
notes?: string;
|
|
71
|
+
source?: string;
|
|
72
|
+
alt?: string;
|
|
73
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
74
|
+
embed?: ChartEmbed;
|
|
75
|
+
/** Value format (labels, tooltips); defaults to locale numbers. */
|
|
76
|
+
format?: (n: number) => string;
|
|
77
|
+
/** Axis tick format; defaults to `format`. */
|
|
78
|
+
tickFormat?: (n: number) => string;
|
|
79
|
+
/** Strip colour; defaults to the highlight colour for highlighted groups and the neutral grey for the rest. */
|
|
80
|
+
color?: (d: T) => string;
|
|
81
|
+
/** x domain; defaults to the lowest and highest published values, rounded. */
|
|
82
|
+
domain?: [number, number];
|
|
83
|
+
/** Height of each row (name and strip), px. */
|
|
84
|
+
rowHeight?: number;
|
|
85
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
86
|
+
annotations?: Snippet<[PlotContext]>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let {
|
|
90
|
+
data,
|
|
91
|
+
label,
|
|
92
|
+
percentiles,
|
|
93
|
+
value = $bindable(),
|
|
94
|
+
highlight,
|
|
95
|
+
inputLabel,
|
|
96
|
+
inputPrefix,
|
|
97
|
+
inputSuffix,
|
|
98
|
+
step,
|
|
99
|
+
min: minValue,
|
|
100
|
+
max: maxValue,
|
|
101
|
+
youLabel,
|
|
102
|
+
readoutLabel,
|
|
103
|
+
readout,
|
|
104
|
+
summary,
|
|
105
|
+
medianLabel,
|
|
106
|
+
middleLabel,
|
|
107
|
+
rangeLabel,
|
|
108
|
+
percentileLabel = (p: number) => `P${p}`,
|
|
109
|
+
style = base,
|
|
110
|
+
locale,
|
|
111
|
+
medium = 'web',
|
|
112
|
+
width,
|
|
113
|
+
title,
|
|
114
|
+
subtitle,
|
|
115
|
+
notes,
|
|
116
|
+
source,
|
|
117
|
+
alt,
|
|
118
|
+
embed,
|
|
119
|
+
format,
|
|
120
|
+
tickFormat,
|
|
121
|
+
color,
|
|
122
|
+
domain,
|
|
123
|
+
rowHeight = 52,
|
|
124
|
+
annotations
|
|
125
|
+
}: Props = $props();
|
|
126
|
+
|
|
127
|
+
const has = (v: Maybe): v is number => v !== null && v !== undefined && Number.isFinite(v);
|
|
128
|
+
const theme = $derived(style);
|
|
129
|
+
const numbers = $derived(createLocale(locale ?? theme.defaultLocale));
|
|
130
|
+
const fmt = $derived(format ?? numbers.number);
|
|
131
|
+
const fontSize = $derived(theme.plot.fontSize);
|
|
132
|
+
const uid = $props.id();
|
|
133
|
+
|
|
134
|
+
/** Each group with its usable points, sorted by percentile. */
|
|
135
|
+
const groups = $derived(
|
|
136
|
+
data.map((d) => {
|
|
137
|
+
const points = percentiles(d)
|
|
138
|
+
.filter((q): q is { p: number; value: number } => has(q.value))
|
|
139
|
+
.toSorted((a, b) => a.p - b.p);
|
|
140
|
+
const at = (p: number) => points.find((q) => q.p === p)?.value;
|
|
141
|
+
return { d, name: label(d), points, median: at(50), q1: at(25), q3: at(75), on: highlight?.(d) ?? false };
|
|
142
|
+
})
|
|
143
|
+
);
|
|
144
|
+
const values = $derived(groups.flatMap((g) => g.points.map((q) => q.value)));
|
|
145
|
+
const x = $derived(
|
|
146
|
+
scaleLinear()
|
|
147
|
+
.domain(domain ?? [min(values) ?? 0, max(values) ?? 1])
|
|
148
|
+
.nice()
|
|
149
|
+
);
|
|
150
|
+
const lo = $derived(minValue ?? x.domain()[0]);
|
|
151
|
+
const hi = $derived(maxValue ?? x.domain()[1]);
|
|
152
|
+
const roundStep = $derived(step ?? 10 ** Math.floor(Math.log10(Math.max(hi - lo, 1e-9) / 100)));
|
|
153
|
+
|
|
154
|
+
const primary = $derived(groups.find((g) => g.on) ?? groups[0]);
|
|
155
|
+
const fallback = $derived(primary?.median ?? primary?.points[Math.floor(primary.points.length / 2)]?.value ?? lo);
|
|
156
|
+
const current = $derived(has(value) ? value : fallback);
|
|
157
|
+
const clamp = (v: number) => Math.min(hi, Math.max(lo, v));
|
|
158
|
+
function set(v: number) {
|
|
159
|
+
if (Number.isFinite(v)) value = v;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const ranks = $derived(groups.map((g) => percentileRank(current, g.points)));
|
|
163
|
+
const percent = $derived(numbers.format('.0f'));
|
|
164
|
+
const readoutText = (rank: PercentileRank | undefined, d: T) => {
|
|
165
|
+
if (!rank) return '–';
|
|
166
|
+
if (readout) return readout(rank, d);
|
|
167
|
+
const n = percent(rank.percentile);
|
|
168
|
+
return rank.below ? `<${n}%` : rank.above ? `>${n}%` : `${n}%`;
|
|
169
|
+
};
|
|
170
|
+
const readouts = $derived(groups.map((g, i) => readoutText(ranks[i], g.d)));
|
|
171
|
+
const summaryText = $derived.by(() => {
|
|
172
|
+
if (!summary || !primary) return '';
|
|
173
|
+
const rank = ranks[groups.indexOf(primary)];
|
|
174
|
+
return rank ? summary(rank, primary.d, current) : '';
|
|
175
|
+
});
|
|
176
|
+
const you = $derived(typeof youLabel === 'function' ? youLabel(fmt(current)) : (youLabel ?? fmt(current)));
|
|
177
|
+
|
|
178
|
+
const stripColor = $derived(
|
|
179
|
+
(g: (typeof groups)[number]) =>
|
|
180
|
+
color?.(g.d) ?? (g.on ? theme.palettes.semantic.highlight : theme.palettes.semantic.neutral)
|
|
181
|
+
);
|
|
182
|
+
const legendColor = $derived(primary ? stripColor(primary) : theme.palettes.semantic.highlight);
|
|
183
|
+
|
|
184
|
+
/** The right-hand column fits the readouts; its heading wraps to the column, above the plot. */
|
|
185
|
+
const headingSize = $derived(fontSize * 0.9);
|
|
186
|
+
const column = $derived(
|
|
187
|
+
Math.max(
|
|
188
|
+
...readouts.map((t) => estimateTextWidth(t, fontSize)),
|
|
189
|
+
...(readoutLabel ?? '').split(/\s+/).map((w) => estimateTextWidth(w, headingSize)),
|
|
190
|
+
readoutLabel ? Math.min(estimateTextWidth(readoutLabel, headingSize), 64) : 0,
|
|
191
|
+
0
|
|
192
|
+
)
|
|
193
|
+
);
|
|
194
|
+
const right = $derived(column + 14);
|
|
195
|
+
const headingLines = $derived.by(() => {
|
|
196
|
+
const lines: string[] = [];
|
|
197
|
+
for (const word of (readoutLabel ?? '').split(/\s+/).filter(Boolean)) {
|
|
198
|
+
const last = lines.at(-1);
|
|
199
|
+
if (last !== undefined && estimateTextWidth(`${last} ${word}`, headingSize) <= column)
|
|
200
|
+
lines[lines.length - 1] = `${last} ${word}`;
|
|
201
|
+
else lines.push(word);
|
|
202
|
+
}
|
|
203
|
+
return lines;
|
|
204
|
+
});
|
|
205
|
+
const lineHeight = $derived(Math.round(headingSize * 1.2));
|
|
206
|
+
const top = $derived(20 + Math.max(0, headingLines.length - 1) * lineHeight);
|
|
207
|
+
const y = $derived(scaleBand<string>().domain(groups.map((g) => g.name)));
|
|
208
|
+
/** Baselines inside a row: the name, then the strip under it. */
|
|
209
|
+
const nameY = $derived(fontSize + 2);
|
|
210
|
+
const stripY = $derived(Math.max(nameY + 18, rowHeight * 0.66));
|
|
211
|
+
|
|
212
|
+
function fromPointer(plot: PlotContext, px: number, event: PointerEvent) {
|
|
213
|
+
if (event.type !== 'pointerdown' && event.buttons === 0) return;
|
|
214
|
+
const raw = plot.x.invert?.(px);
|
|
215
|
+
if (typeof raw === 'number') set(clamp(Math.round(raw / roundStep) * roundStep));
|
|
216
|
+
}
|
|
217
|
+
</script>
|
|
218
|
+
|
|
219
|
+
<Chart {style} {locale} {medium} {width} {alt} {embed}>
|
|
220
|
+
<Header>
|
|
221
|
+
{#if title}<Title>{title}</Title>{/if}
|
|
222
|
+
{#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
|
|
223
|
+
{#if medium !== 'print'}
|
|
224
|
+
<div class="mz-percentile-controls">
|
|
225
|
+
<label class="mz-percentile-input" for="{uid}-value">
|
|
226
|
+
{#if inputLabel}<span class="mz-percentile-input-label">{inputLabel}</span>{/if}
|
|
227
|
+
<span class="mz-percentile-field">
|
|
228
|
+
{#if inputPrefix}<span aria-hidden="true">{inputPrefix}</span>{/if}
|
|
229
|
+
<input
|
|
230
|
+
id="{uid}-value"
|
|
231
|
+
type="number"
|
|
232
|
+
inputmode="decimal"
|
|
233
|
+
min={lo}
|
|
234
|
+
max={hi}
|
|
235
|
+
step="any"
|
|
236
|
+
value={current}
|
|
237
|
+
aria-label={inputLabel ? undefined : you}
|
|
238
|
+
oninput={(e) => set(e.currentTarget.valueAsNumber)}
|
|
239
|
+
/>
|
|
240
|
+
{#if inputSuffix}<span aria-hidden="true">{inputSuffix}</span>{/if}
|
|
241
|
+
</span>
|
|
242
|
+
</label>
|
|
243
|
+
<input
|
|
244
|
+
class="mz-percentile-slider"
|
|
245
|
+
type="range"
|
|
246
|
+
min={lo}
|
|
247
|
+
max={hi}
|
|
248
|
+
step={roundStep}
|
|
249
|
+
value={clamp(current)}
|
|
250
|
+
aria-label={inputLabel ?? you}
|
|
251
|
+
aria-valuetext={fmt(current)}
|
|
252
|
+
oninput={(e) => set(e.currentTarget.valueAsNumber)}
|
|
253
|
+
/>
|
|
254
|
+
</div>
|
|
255
|
+
{/if}
|
|
256
|
+
{#if summaryText}<p class="mz-percentile-summary" aria-live="polite">{summaryText}</p>{/if}
|
|
257
|
+
{#if medianLabel || middleLabel || rangeLabel}
|
|
258
|
+
<div class="mz-percentile-legend">
|
|
259
|
+
{#if medianLabel}<Legend shape="circle" items={[{ label: medianLabel, color: legendColor }]} />{/if}
|
|
260
|
+
{#if middleLabel}<Legend items={[{ label: middleLabel, color: legendColor }]} />{/if}
|
|
261
|
+
{#if rangeLabel}<Legend shape="line" items={[{ label: rangeLabel, color: legendColor }]} />{/if}
|
|
262
|
+
</div>
|
|
263
|
+
{/if}
|
|
264
|
+
</Header>
|
|
265
|
+
|
|
266
|
+
<Plot {x} {y} height={groups.length * rowHeight} padding={{ left: 4, right, top, bottom: 24 }}>
|
|
267
|
+
{#snippet children(plot)}
|
|
268
|
+
{@const yx = clamp(current)}
|
|
269
|
+
{@const px = plot.x(Math.min(x.domain()[1], Math.max(x.domain()[0], yx))) ?? 0}
|
|
270
|
+
{@const anchor = px > plot.width * 0.8 ? 'end' : px < plot.width * 0.2 ? 'start' : 'middle'}
|
|
271
|
+
<Svg>
|
|
272
|
+
<GridX ticks={4} />
|
|
273
|
+
<AxisX ticks={4} format={tickFormat ?? fmt} />
|
|
274
|
+
<PointerArea onmove={({ x: p, event }) => fromPointer(plot, p, event)} />
|
|
275
|
+
<!-- Above the plot, in the right-hand column (clear of the "you" label, which stays over the plot area). -->
|
|
276
|
+
{#each headingLines as line, i (i)}
|
|
277
|
+
<text
|
|
278
|
+
class="mz-percentile-heading"
|
|
279
|
+
x={plot.width + right}
|
|
280
|
+
y={-8 - (headingLines.length - 1 - i) * lineHeight}
|
|
281
|
+
text-anchor="end">{line}</text
|
|
282
|
+
>
|
|
283
|
+
{/each}
|
|
284
|
+
<!-- Under the rows, so group names (with a background halo) and dots sit on top of it. -->
|
|
285
|
+
<line class="mz-percentile-you" x1={px} x2={px} y1={-4} y2={plot.height} />
|
|
286
|
+
{#each groups as g, i (g.name)}
|
|
287
|
+
{@const rowTop = plot.y(g.name) ?? 0}
|
|
288
|
+
{@const c = stripColor(g)}
|
|
289
|
+
{@const first = g.points[0]}
|
|
290
|
+
{@const last = g.points[g.points.length - 1]}
|
|
291
|
+
<g class="mz-percentile-row" class:on={g.on} transform="translate(0,{rowTop})">
|
|
292
|
+
<text class="mz-percentile-name" y={nameY}>{g.name}</text>
|
|
293
|
+
{#if first && last}
|
|
294
|
+
<line
|
|
295
|
+
x1={plot.x(first.value)}
|
|
296
|
+
x2={plot.x(last.value)}
|
|
297
|
+
y1={stripY}
|
|
298
|
+
y2={stripY}
|
|
299
|
+
stroke={c}
|
|
300
|
+
stroke-width="2"
|
|
301
|
+
stroke-opacity="0.5"
|
|
302
|
+
/>
|
|
303
|
+
{/if}
|
|
304
|
+
{#if has(g.q1) && has(g.q3)}
|
|
305
|
+
<line
|
|
306
|
+
x1={plot.x(g.q1)}
|
|
307
|
+
x2={plot.x(g.q3)}
|
|
308
|
+
y1={stripY}
|
|
309
|
+
y2={stripY}
|
|
310
|
+
stroke={c}
|
|
311
|
+
stroke-width="10"
|
|
312
|
+
stroke-opacity="0.35"
|
|
313
|
+
/>
|
|
314
|
+
{/if}
|
|
315
|
+
{#each g.points.filter((q) => q.p !== 50) as q (q.p)}
|
|
316
|
+
<circle cx={plot.x(q.value)} cy={stripY} r="3" fill={c}>
|
|
317
|
+
<title>{g.name}, {percentileLabel(q.p)}: {fmt(q.value)}</title>
|
|
318
|
+
</circle>
|
|
319
|
+
{/each}
|
|
320
|
+
{#if has(g.median)}
|
|
321
|
+
<circle
|
|
322
|
+
cx={plot.x(g.median)}
|
|
323
|
+
cy={stripY}
|
|
324
|
+
r="6.5"
|
|
325
|
+
fill={c}
|
|
326
|
+
stroke={theme.tokens['--mz-color-bg']}
|
|
327
|
+
stroke-width="1.5"
|
|
328
|
+
>
|
|
329
|
+
<title>{g.name}, {medianLabel ?? percentileLabel(50)}: {fmt(g.median)}</title>
|
|
330
|
+
</circle>
|
|
331
|
+
{/if}
|
|
332
|
+
<text class="mz-percentile-readout" x={plot.width + right} y={stripY} dy="0.35em" text-anchor="end"
|
|
333
|
+
>{readouts[i]}</text
|
|
334
|
+
>
|
|
335
|
+
</g>
|
|
336
|
+
{/each}
|
|
337
|
+
<text class="mz-percentile-you-label" x={px} y={-8} text-anchor={anchor}>{you}</text>
|
|
338
|
+
{@render annotations?.(plot)}
|
|
339
|
+
</Svg>
|
|
340
|
+
{/snippet}
|
|
341
|
+
</Plot>
|
|
342
|
+
|
|
343
|
+
{#if notes || source}
|
|
344
|
+
<Footer>
|
|
345
|
+
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
346
|
+
{#if source}<Source>{source}</Source>{/if}
|
|
347
|
+
</Footer>
|
|
348
|
+
{/if}
|
|
349
|
+
</Chart>
|
|
350
|
+
|
|
351
|
+
<style>
|
|
352
|
+
.mz-percentile-controls {
|
|
353
|
+
display: flex;
|
|
354
|
+
flex-wrap: wrap;
|
|
355
|
+
align-items: center;
|
|
356
|
+
gap: 0.5rem 1rem;
|
|
357
|
+
font-family: var(--mz-font-label);
|
|
358
|
+
font-size: var(--mz-size-small);
|
|
359
|
+
}
|
|
360
|
+
.mz-percentile-input {
|
|
361
|
+
display: inline-flex;
|
|
362
|
+
align-items: center;
|
|
363
|
+
gap: 0.5rem;
|
|
364
|
+
color: var(--mz-color-text);
|
|
365
|
+
}
|
|
366
|
+
.mz-percentile-input-label {
|
|
367
|
+
font-weight: var(--mz-weight-label);
|
|
368
|
+
text-transform: var(--mz-label-transform);
|
|
369
|
+
letter-spacing: var(--mz-label-tracking);
|
|
370
|
+
}
|
|
371
|
+
.mz-percentile-field {
|
|
372
|
+
display: inline-flex;
|
|
373
|
+
align-items: center;
|
|
374
|
+
gap: 0.25rem;
|
|
375
|
+
padding: 0.2rem 0.5rem;
|
|
376
|
+
border: 1px solid var(--mz-color-axis);
|
|
377
|
+
border-radius: var(--mz-radius);
|
|
378
|
+
background: var(--mz-color-bg);
|
|
379
|
+
}
|
|
380
|
+
.mz-percentile-field:focus-within {
|
|
381
|
+
outline: 2px solid var(--mz-color-accent);
|
|
382
|
+
outline-offset: 1px;
|
|
383
|
+
}
|
|
384
|
+
.mz-percentile-field input {
|
|
385
|
+
width: 7ch;
|
|
386
|
+
border: 0;
|
|
387
|
+
padding: 0;
|
|
388
|
+
background: transparent;
|
|
389
|
+
color: var(--mz-color-text);
|
|
390
|
+
font: inherit;
|
|
391
|
+
font-size: var(--mz-size-body);
|
|
392
|
+
font-weight: var(--mz-weight-strong);
|
|
393
|
+
font-variant-numeric: tabular-nums;
|
|
394
|
+
outline: none;
|
|
395
|
+
appearance: textfield;
|
|
396
|
+
-moz-appearance: textfield;
|
|
397
|
+
}
|
|
398
|
+
.mz-percentile-field input::-webkit-inner-spin-button,
|
|
399
|
+
.mz-percentile-field input::-webkit-outer-spin-button {
|
|
400
|
+
-webkit-appearance: none;
|
|
401
|
+
margin: 0;
|
|
402
|
+
}
|
|
403
|
+
.mz-percentile-slider {
|
|
404
|
+
flex: 1 1 10rem;
|
|
405
|
+
min-width: 8rem;
|
|
406
|
+
max-width: 22rem;
|
|
407
|
+
accent-color: var(--mz-color-accent);
|
|
408
|
+
}
|
|
409
|
+
.mz-percentile-summary {
|
|
410
|
+
margin: 0;
|
|
411
|
+
font-family: var(--mz-font-body);
|
|
412
|
+
font-size: var(--mz-size-body);
|
|
413
|
+
color: var(--mz-color-text);
|
|
414
|
+
}
|
|
415
|
+
.mz-percentile-legend {
|
|
416
|
+
display: flex;
|
|
417
|
+
flex-wrap: wrap;
|
|
418
|
+
gap: 0 1rem;
|
|
419
|
+
}
|
|
420
|
+
.mz-percentile-name,
|
|
421
|
+
.mz-percentile-readout,
|
|
422
|
+
.mz-percentile-heading,
|
|
423
|
+
.mz-percentile-you-label {
|
|
424
|
+
font-family: var(--mz-font-body);
|
|
425
|
+
font-size: var(--mz-size-axis);
|
|
426
|
+
fill: var(--mz-color-text);
|
|
427
|
+
}
|
|
428
|
+
.on .mz-percentile-name,
|
|
429
|
+
.mz-percentile-readout,
|
|
430
|
+
.mz-percentile-you-label {
|
|
431
|
+
font-weight: var(--mz-weight-strong);
|
|
432
|
+
}
|
|
433
|
+
/* A background-coloured outline keeps names legible where the "you" line crosses them. */
|
|
434
|
+
.mz-percentile-name {
|
|
435
|
+
paint-order: stroke;
|
|
436
|
+
stroke: var(--mz-color-bg);
|
|
437
|
+
stroke-width: 4px;
|
|
438
|
+
stroke-linejoin: round;
|
|
439
|
+
}
|
|
440
|
+
.mz-percentile-readout {
|
|
441
|
+
font-variant-numeric: tabular-nums;
|
|
442
|
+
}
|
|
443
|
+
.mz-percentile-heading {
|
|
444
|
+
fill: var(--mz-color-muted);
|
|
445
|
+
font-size: calc(var(--mz-size-axis) * 0.9);
|
|
446
|
+
}
|
|
447
|
+
.mz-percentile-you {
|
|
448
|
+
stroke: var(--mz-color-text);
|
|
449
|
+
stroke-width: 1.5;
|
|
450
|
+
pointer-events: none;
|
|
451
|
+
}
|
|
452
|
+
</style>
|
package/src/lib/recipes/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ export { default as ArrowChart } from './ArrowChart.svelte';
|
|
|
6
6
|
export { default as BarDotChart } from './BarDotChart.svelte';
|
|
7
7
|
export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
|
+
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
9
10
|
|
|
10
11
|
/** Recipe names accepted by `mozaic eject`. */
|
|
11
12
|
export const recipes = [
|
|
@@ -16,5 +17,6 @@ export const recipes = [
|
|
|
16
17
|
'ArrowChart',
|
|
17
18
|
'BarDotChart',
|
|
18
19
|
'StackedBarChart',
|
|
19
|
-
'MosaicChart'
|
|
20
|
+
'MosaicChart',
|
|
21
|
+
'PercentileChart'
|
|
20
22
|
] as const;
|