@vitavision/charts 0.8.3 → 0.8.4

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.
@@ -0,0 +1,416 @@
1
+ /**
2
+ * A scatter plot: points over two numeric axes, each optionally coloured by a third value.
3
+ *
4
+ * Points are drawn as a few batched paths (one per series, or one per colour step with
5
+ * `colourBy`), never one element per point, and the pointer is resolved from the projected
6
+ * positions, not from the DOM. A few thousand points stay cheap.
7
+ */
8
+
9
+ import { useId, useMemo, useState, type ReactNode } from "react";
10
+
11
+ import { toneColor, type MeasureTone } from "@vitavision/ui";
12
+
13
+ import { ColormapLegend } from "./ColormapLegend";
14
+ import { colormapRgb, isDivergingColormap, type ColormapName } from "./colormap";
15
+ import { FLUID_DEFAULT_HEIGHT, Frame, Legend, areaFor, seriesColour, useFluidSize, type Variant } from "./Frame";
16
+ import { extent, linearScale, type Scale } from "./scale";
17
+ import { SCATTER_COLOUR_STEPS, colourDomain, colourStep, nearestProjected } from "./scatter";
18
+
19
+ /** One point of a {@link ScatterChart}. */
20
+ export interface ScatterPoint {
21
+ /** Horizontal position, in x domain units. A non-finite value skips the point. */
22
+ x: number;
23
+ /** Vertical position, in y domain units. A non-finite value skips the point. */
24
+ y: number;
25
+ /** What `colourBy` colours it by. A point without one is drawn in the muted tone. */
26
+ value?: number | undefined;
27
+ }
28
+
29
+ /** One group of points of a {@link ScatterChart}. */
30
+ export interface ScatterSeries {
31
+ /** Legend text, and the React key — unique within one chart. */
32
+ name: string;
33
+ /** The points. Their index here is what hover and pick report. */
34
+ points: readonly ScatterPoint[];
35
+ /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. Ignored with `colourBy`. */
36
+ colour?: string | undefined;
37
+ }
38
+
39
+ /** Colour every point by its `value` through a map. */
40
+ export interface ScatterColourBy {
41
+ /** The map. A diverging map centres on zero by default. */
42
+ map: ColormapName;
43
+ /** The values at the map's ends. Omitted: the extent of the points' values. */
44
+ domain?: readonly [number, number] | undefined;
45
+ /** Centre the domain on zero. Defaults to `true` for a diverging map, `false` otherwise. */
46
+ symmetric?: boolean | undefined;
47
+ /** What the colour encodes, written beside the scale. Required: a map is never shown unlabelled. */
48
+ label: string;
49
+ /** The values' unit, written after the scale's numbers. */
50
+ unit?: string | undefined;
51
+ }
52
+
53
+ /** A rule across the plot at one x or y: a tolerance, a mean, an expected value. */
54
+ export interface ScatterReferenceLine {
55
+ /** Which axis the value is on: `"y"` is a horizontal rule, `"x"` a vertical one. */
56
+ axis: "x" | "y";
57
+ /** Where, in that axis' domain units. A value outside the domain is not drawn. */
58
+ value: number;
59
+ /** Text at the rule's end. */
60
+ label?: string | undefined;
61
+ /** Its colour. Default `"muted"`. */
62
+ tone?: MeasureTone | undefined;
63
+ }
64
+
65
+ /** A point of a {@link ScatterChart}, as hover and pick report it. */
66
+ export interface ScatterPick {
67
+ /** The name of its series. */
68
+ series: string;
69
+ /** Its index in that series' `points`. */
70
+ index: number;
71
+ /** Its x. */
72
+ x: number;
73
+ /** Its y. */
74
+ y: number;
75
+ /** Its value, when it has one. */
76
+ value?: number | undefined;
77
+ }
78
+
79
+ /** Props for {@link ScatterChart}. */
80
+ export interface ScatterChartProps {
81
+ /** The groups of points, drawn in order — a later series paints over an earlier one. */
82
+ series: readonly ScatterSeries[];
83
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
84
+ label: string;
85
+ /** x-axis title. */
86
+ xLabel?: string | undefined;
87
+ /** y-axis title. */
88
+ yLabel?: string | undefined;
89
+ /** Fixed x domain. Omitted: the extent of every series' `x`, with 4 % on each side. */
90
+ xDomain?: [number, number] | undefined;
91
+ /** Fixed y domain. Omitted: the extent of every series' `y`, with 4 % on each side. */
92
+ yDomain?: [number, number] | undefined;
93
+ /** Colour points by their `value`, with a legend of the scale in the footer. */
94
+ colourBy?: ScatterColourBy | undefined;
95
+ /** Rules across the plot, drawn behind the points. */
96
+ referenceLines?: readonly ScatterReferenceLine[] | undefined;
97
+ /** Marker diameter in CSS pixels at the chart's own scale. Default 4. */
98
+ markerSize?: number | undefined;
99
+ /** Drawn behind the points, in plot pixels. A tolerance region or a fitted curve uses this. */
100
+ underlay?: ((x: Scale, y: Scale) => ReactNode) | undefined;
101
+ /** The point to draw as highlighted, from outside the chart (a hovered table row). */
102
+ highlighted?: { series: string; index: number } | null | undefined;
103
+ /**
104
+ * Called with the point nearest the pointer (within 10 plot units), or `null` when none is.
105
+ * Draws a ring on it and a readout of its numbers.
106
+ */
107
+ onHover?: ((point: ScatterPick | null) => void) | undefined;
108
+ /** Called with the point under a click. Makes the plot area a pointer target. */
109
+ onPick?: ((point: ScatterPick) => void) | undefined;
110
+ /** Rendered under the legend, inside the `<figcaption>`. */
111
+ footer?: ReactNode;
112
+ /** Show the series legend row (without `colourBy`). Default `true`. */
113
+ showLegend?: boolean | undefined;
114
+ /** Where the chart is going (see {@link Variant}). Default `"panel"`. */
115
+ variant?: Variant | undefined;
116
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
117
+ className?: string | undefined;
118
+ /** For `variant="fluid"`: the chart's height in CSS pixels. Default 200. */
119
+ height?: number | undefined;
120
+ }
121
+
122
+ /** How near the pointer must be to a point, in viewBox units, to pick it. */
123
+ const PICK_RADIUS = 10;
124
+ const MUTED = "var(--fg-subtle)";
125
+
126
+ const formatValue = (value: number) => (Math.abs(value) >= 100 ? value.toFixed(0) : String(Number(value.toPrecision(3))));
127
+
128
+ /**
129
+ * A scatter plot over a shared frame — residuals against position, one run against another.
130
+ *
131
+ * @remarks
132
+ * An SVG `role="img"` named by `label`, with the series legend (or, with `colourBy`, the colour
133
+ * scale) as real text under it. Series are told apart by the legend's names, never by colour
134
+ * alone. `referenceLines` mark a value on either axis; `onHover` rings the nearest point and
135
+ * reads its numbers, `onPick` reports a click's point, and `highlighted` rings one chosen
136
+ * elsewhere. Picking is by pointer, so the same points must be reachable from a table beside
137
+ * the chart. A point with a non-finite coordinate is skipped.
138
+ */
139
+ export function ScatterChart({
140
+ series,
141
+ label,
142
+ xLabel,
143
+ yLabel,
144
+ xDomain,
145
+ yDomain,
146
+ colourBy,
147
+ referenceLines,
148
+ markerSize = 4,
149
+ underlay,
150
+ highlighted,
151
+ onHover,
152
+ onPick,
153
+ footer,
154
+ showLegend = true,
155
+ variant = "panel",
156
+ className,
157
+ height = FLUID_DEFAULT_HEIGHT,
158
+ }: ScatterChartProps) {
159
+ const clipId = useId();
160
+ const [fluidRef, fluidSize] = useFluidSize(height);
161
+ const size = variant === "fluid" ? fluidSize : undefined;
162
+ const area = areaFor(variant, size);
163
+
164
+ const allX: number[] = [];
165
+ const allY: number[] = [];
166
+ for (const entry of series) {
167
+ for (const p of entry.points) {
168
+ allX.push(p.x);
169
+ allY.push(p.y);
170
+ }
171
+ }
172
+ const xScale = linearScale(xDomain ?? paddedExtent(allX), area.x0, area.x1);
173
+ const yScale = linearScale(yDomain ?? paddedExtent(allY), area.y0, area.y1);
174
+
175
+ const symmetric = colourBy ? (colourBy.symmetric ?? isDivergingColormap(colourBy.map)) : false;
176
+ const domain = useMemo(
177
+ () =>
178
+ colourBy
179
+ ? colourDomain(
180
+ series.flatMap((s) => s.points.map((p) => p.value ?? Number.NaN)),
181
+ symmetric,
182
+ colourBy.domain,
183
+ )
184
+ : null,
185
+ [series, colourBy, symmetric],
186
+ );
187
+
188
+ // Projected positions, once per data or geometry change: they are what drawing and picking read.
189
+ const projected = useMemo(() => {
190
+ const xy: number[] = [];
191
+ const owner: { series: number; index: number }[] = [];
192
+ series.forEach((entry, s) => {
193
+ entry.points.forEach((p, index) => {
194
+ const px = xScale.project(p.x);
195
+ const py = yScale.project(p.y);
196
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y) || !Number.isFinite(px) || !Number.isFinite(py)) return;
197
+ xy.push(px, py);
198
+ owner.push({ series: s, index });
199
+ });
200
+ });
201
+ return { xy, owner };
202
+ // The scales are rebuilt every render from their domains and the area; these are what they depend on.
203
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
204
+ }, [series, xScale.domain[0], xScale.domain[1], yScale.domain[0], yScale.domain[1], area.x0, area.x1, area.y0, area.y1]);
205
+
206
+ // One batched path per (series, colour step).
207
+ const batches = useMemo(() => {
208
+ const out: { key: string; d: string; colour: string }[] = [];
209
+ let cursor = 0;
210
+ series.forEach((entry, s) => {
211
+ const parts = new Map<number, string>();
212
+ while (cursor < projected.owner.length && projected.owner[cursor]!.series === s) {
213
+ const point = entry.points[projected.owner[cursor]!.index]!;
214
+ const step = colourBy && domain ? colourStep(point.value ?? Number.NaN, domain) : 0;
215
+ parts.set(step, `${parts.get(step) ?? ""}M${projected.xy[2 * cursor]!.toFixed(2)} ${projected.xy[2 * cursor + 1]!.toFixed(2)}h0`);
216
+ cursor++;
217
+ }
218
+ for (const [step, d] of parts) {
219
+ let colour: string;
220
+ if (!colourBy) colour = entry.colour ?? seriesColour(s);
221
+ else if (step < 0) colour = MUTED;
222
+ else {
223
+ const [r, g, b] = colormapRgb(colourBy.map, (step + 0.5) / SCATTER_COLOUR_STEPS);
224
+ colour = `rgb(${r} ${g} ${b})`;
225
+ }
226
+ out.push({ key: `${s}|${step}`, d, colour });
227
+ }
228
+ });
229
+ return out;
230
+ }, [series, projected, colourBy, domain]);
231
+
232
+ const [hover, setHover] = useState<ScatterPick | null>(null);
233
+ const pickAt = (event: { clientX: number; clientY: number; currentTarget: SVGRectElement }): ScatterPick | null => {
234
+ const svg = event.currentTarget.ownerSVGElement;
235
+ const ctm = svg?.getScreenCTM();
236
+ let x = event.clientX;
237
+ let y = event.clientY;
238
+ if (svg && ctm) {
239
+ const point = svg.createSVGPoint();
240
+ point.x = event.clientX;
241
+ point.y = event.clientY;
242
+ const local = point.matrixTransform(ctm.inverse());
243
+ x = local.x;
244
+ y = local.y;
245
+ }
246
+ const found = nearestProjected(projected.xy, x, y, PICK_RADIUS);
247
+ return found < 0 ? null : pointOf(found);
248
+ };
249
+ const pointOf = (k: number): ScatterPick => {
250
+ const { series: s, index } = projected.owner[k]!;
251
+ const entry = series[s]!;
252
+ const point = entry.points[index]!;
253
+ return { series: entry.name, index, x: point.x, y: point.y, value: point.value };
254
+ };
255
+
256
+ const ringed = hover ?? (highlighted ? findPick(series, highlighted) : null);
257
+ const ringAt = ringed ? { cx: xScale.project(ringed.x), cy: yScale.project(ringed.y) } : null;
258
+ const interactive = onHover !== undefined || onPick !== undefined;
259
+ const radius = markerSize / 2;
260
+
261
+ return (
262
+ <Frame
263
+ xScale={xScale}
264
+ yScale={yScale}
265
+ xLabel={xLabel}
266
+ yLabel={yLabel}
267
+ label={label}
268
+ variant={variant}
269
+ className={className}
270
+ size={size}
271
+ figureRef={variant === "fluid" ? fluidRef : undefined}
272
+ footer={
273
+ <div className="flex flex-col gap-1">
274
+ {colourBy && domain ? (
275
+ <ColormapLegend
276
+ map={colourBy.map}
277
+ domain={domain}
278
+ label={colourBy.label}
279
+ unit={colourBy.unit}
280
+ symmetric={symmetric}
281
+ format={formatValue}
282
+ />
283
+ ) : (
284
+ showLegend && <Legend items={series.map((entry, s) => ({ label: entry.name, colour: entry.colour ?? seriesColour(s) }))} />
285
+ )}
286
+ {footer}
287
+ </div>
288
+ }
289
+ >
290
+ <defs>
291
+ <clipPath id={clipId}>
292
+ <rect x={area.x0} y={area.y1} width={area.x1 - area.x0} height={area.y0 - area.y1} />
293
+ </clipPath>
294
+ </defs>
295
+ {underlay?.(xScale, yScale)}
296
+ {referenceLines && referenceLines.length > 0 && <ReferenceLines lines={referenceLines} xScale={xScale} yScale={yScale} area={area} />}
297
+ <g clipPath={`url(#${clipId})`} data-points="" fill="none" strokeLinecap="round">
298
+ {batches.map((batch) => (
299
+ <path key={batch.key} d={batch.d} stroke="var(--surface)" strokeWidth={markerSize + 1.5} opacity={0.7} />
300
+ ))}
301
+ {batches.map((batch) => (
302
+ <path key={`p|${batch.key}`} data-batch={batch.key} d={batch.d} stroke={batch.colour} strokeWidth={markerSize} />
303
+ ))}
304
+ </g>
305
+ {ringAt && (
306
+ <g data-highlight="" pointerEvents="none">
307
+ <circle {...ringAt} r={radius + 3} fill="none" stroke="var(--surface)" strokeWidth={3.5} />
308
+ <circle {...ringAt} r={radius + 3} fill="none" stroke="var(--signal)" strokeWidth={1.75} />
309
+ </g>
310
+ )}
311
+ {hover && (
312
+ <text
313
+ data-readout=""
314
+ x={xScale.project(hover.x) > (area.x0 + area.x1) / 2 ? area.x1 - 4 : area.x0 + 4}
315
+ y={area.y1 + 10}
316
+ textAnchor={xScale.project(hover.x) > (area.x0 + area.x1) / 2 ? "end" : "start"}
317
+ fontSize={10}
318
+ fill="currentColor"
319
+ >
320
+ {[`${formatValue(hover.x)}, ${formatValue(hover.y)}`, hover.value !== undefined ? formatValue(hover.value) : null]
321
+ .filter((part) => part !== null)
322
+ .join(" · ")}
323
+ </text>
324
+ )}
325
+ {interactive && (
326
+ <rect
327
+ data-plot-target=""
328
+ x={area.x0}
329
+ y={area.y1}
330
+ width={area.x1 - area.x0}
331
+ height={area.y0 - area.y1}
332
+ fill="transparent"
333
+ style={{ cursor: onPick ? "pointer" : "crosshair" }}
334
+ onPointerMove={(event) => {
335
+ const next = pickAt(event);
336
+ setHover(next);
337
+ onHover?.(next);
338
+ }}
339
+ onPointerLeave={() => {
340
+ setHover(null);
341
+ onHover?.(null);
342
+ }}
343
+ onClick={(event) => {
344
+ const picked = pickAt(event);
345
+ if (picked) onPick?.(picked);
346
+ }}
347
+ />
348
+ )}
349
+ </Frame>
350
+ );
351
+ }
352
+
353
+ /** The extent of the values with 4 % on each side, so a marker on an extreme is not cut by the axis or the frame. */
354
+ function paddedExtent(values: readonly number[]): [number, number] {
355
+ const [low, high] = extent(values);
356
+ const pad = (high - low) * 0.04;
357
+ return [low - pad, high + pad];
358
+ }
359
+
360
+ /** The point a `highlighted` names, or `null` when it names none that exists and is finite. */
361
+ function findPick(series: readonly ScatterSeries[], at: { series: string; index: number }): ScatterPick | null {
362
+ const entry = series.find((s) => s.name === at.series);
363
+ const point = entry?.points[at.index];
364
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;
365
+ return { series: at.series, index: at.index, x: point.x, y: point.y, value: point.value };
366
+ }
367
+
368
+ /** Dashed rules across the plot, with their labels at the end. */
369
+ function ReferenceLines({
370
+ lines,
371
+ xScale,
372
+ yScale,
373
+ area,
374
+ }: {
375
+ lines: readonly ScatterReferenceLine[];
376
+ xScale: Scale;
377
+ yScale: Scale;
378
+ area: { x0: number; x1: number; y0: number; y1: number };
379
+ }) {
380
+ return (
381
+ <g data-reference-lines="">
382
+ {lines.map((line) => {
383
+ const horizontal = line.axis === "y";
384
+ const scale = horizontal ? yScale : xScale;
385
+ const at = scale.project(line.value);
386
+ const [lo, hi] = horizontal ? [area.y1, area.y0] : [area.x0, area.x1];
387
+ if (!Number.isFinite(at) || at < Math.min(lo, hi) - 0.5 || at > Math.max(lo, hi) + 0.5) return null;
388
+ const colour = toneColor(line.tone, "muted");
389
+ return (
390
+ <g key={`${line.axis}|${line.value}|${line.label ?? ""}`} data-reference-line={line.axis}>
391
+ <line
392
+ x1={horizontal ? area.x0 : at}
393
+ x2={horizontal ? area.x1 : at}
394
+ y1={horizontal ? at : area.y0}
395
+ y2={horizontal ? at : area.y1}
396
+ stroke={colour}
397
+ strokeWidth={1.25}
398
+ strokeDasharray="3 2"
399
+ />
400
+ {line.label && (
401
+ <text
402
+ x={horizontal ? area.x1 - 3 : at + 3}
403
+ y={horizontal ? at - 3 : area.y1 + 10}
404
+ textAnchor={horizontal ? "end" : "start"}
405
+ fontSize={9}
406
+ fill={colour}
407
+ >
408
+ {line.label}
409
+ </text>
410
+ )}
411
+ </g>
412
+ );
413
+ })}
414
+ </g>
415
+ );
416
+ }
package/src/band.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The arithmetic of a series' error band: the ribbon between a lower and an upper value at every
3
+ * point of a series, its outline, and its value at an x between two points. Pure, so the geometry
4
+ * is testable apart from the SVG.
5
+ */
6
+
7
+ import { seriesValueAt } from "./interpolate";
8
+ import type { Scale } from "./scale";
9
+
10
+ /** A series' band: the values either side of its line, one per point, by index. */
11
+ export interface SeriesBand {
12
+ /** The lower edge at each point. A non-finite value breaks the band there. */
13
+ lower: readonly number[];
14
+ /** The upper edge at each point. */
15
+ upper: readonly number[];
16
+ /** What the legend says after the series' name. Default `"± band"`. */
17
+ label?: string | undefined;
18
+ }
19
+
20
+ /** The band's edges at point `index`, ordered low to high, or `null` where either is missing or non-finite. */
21
+ export function bandBoundsAt(band: Pick<SeriesBand, "lower" | "upper">, index: number): [number, number] | null {
22
+ const a = band.lower[index];
23
+ const b = band.upper[index];
24
+ if (a === undefined || b === undefined || !Number.isFinite(a) || !Number.isFinite(b)) return null;
25
+ return a <= b ? [a, b] : [b, a];
26
+ }
27
+
28
+ /**
29
+ * The outline of a band as an SVG path `d`: the upper edge left to right and the lower edge back,
30
+ * closed, once for every run of points whose x and both edges are finite. A run of one point has
31
+ * no area and draws nothing; a gap ends the run, so the band is not bridged across missing data.
32
+ *
33
+ * @param points - The series' points, in draw order.
34
+ * @param band - The edges, by point index. Missing entries count as gaps.
35
+ * @param xScale - The horizontal scale.
36
+ * @param yScale - The vertical scale.
37
+ * @returns The path, or `""` when there is nothing to fill.
38
+ */
39
+ export function bandPath(
40
+ points: readonly { x: number; y: number }[],
41
+ band: Pick<SeriesBand, "lower" | "upper">,
42
+ xScale: Scale,
43
+ yScale: Scale,
44
+ ): string {
45
+ const runs: { x: number; lo: number; hi: number }[][] = [];
46
+ let run: { x: number; lo: number; hi: number }[] = [];
47
+ const close = () => {
48
+ if (run.length > 1) runs.push(run);
49
+ run = [];
50
+ };
51
+ points.forEach((point, index) => {
52
+ const bounds = bandBoundsAt(band, index);
53
+ if (!Number.isFinite(point.x) || bounds === null) {
54
+ close();
55
+ return;
56
+ }
57
+ run.push({ x: xScale.project(point.x), lo: yScale.project(bounds[0]), hi: yScale.project(bounds[1]) });
58
+ });
59
+ close();
60
+ const f = (n: number) => n.toFixed(2);
61
+ return runs
62
+ .map((r) => {
63
+ const top = r.map((p, i) => `${i === 0 ? "M" : "L"}${f(p.x)} ${f(p.hi)}`);
64
+ const bottom = r.map((p) => `L${f(p.x)} ${f(p.lo)}`).reverse();
65
+ return `${[...top, ...bottom].join(" ")} Z`;
66
+ })
67
+ .join(" ");
68
+ }
69
+
70
+ /** Every finite edge of a band, for the chart's y extent. */
71
+ export function bandValues(band: Pick<SeriesBand, "lower" | "upper">): number[] {
72
+ return [...band.lower, ...band.upper].filter(Number.isFinite);
73
+ }
74
+
75
+ /** A series' band at `x`, interpolated like {@link seriesValueAt}: `[lower, upper]`, or `null` outside the series or across a gap. */
76
+ export function bandValueAt(
77
+ points: readonly { x: number; y: number }[],
78
+ band: Pick<SeriesBand, "lower" | "upper">,
79
+ x: number,
80
+ ): [number, number] | null {
81
+ const edge = (pick: 0 | 1) =>
82
+ seriesValueAt(
83
+ points.map((point, index) => ({ x: point.x, y: bandBoundsAt(band, index)?.[pick] ?? Number.NaN })),
84
+ x,
85
+ );
86
+ const lo = edge(0);
87
+ const hi = edge(1);
88
+ return lo === null || hi === null ? null : [lo, hi];
89
+ }
90
+
91
+ /**
92
+ * A value with its band as text: `3.2 ± 0.4` when the band is symmetric about the value, else
93
+ * `3.2 [2.8, 3.9]`.
94
+ *
95
+ * @param value - The series' value.
96
+ * @param bounds - The band's `[lower, upper]` there.
97
+ * @param format - Formats one number.
98
+ */
99
+ export function formatWithBand(value: number, bounds: readonly [number, number], format: (n: number) => string): string {
100
+ const [lo, hi] = bounds;
101
+ const up = hi - value;
102
+ const down = value - lo;
103
+ const symmetric = Math.abs(up - down) <= 1e-6 * Math.max(Math.abs(up), Math.abs(down), Number.MIN_VALUE);
104
+ return symmetric ? `${format(value)} ± ${format(up)}` : `${format(value)} [${format(lo)}, ${format(hi)}]`;
105
+ }
package/src/colormap.ts CHANGED
@@ -1,21 +1,33 @@
1
1
  /**
2
- * Sequential colour maps for a magnitude: a residual's size, a per-cell
3
- * error, a confidence, a validity fraction.
2
+ * Colour maps for a magnitude: a residual's size, a per-cell error, a confidence, a validity
3
+ * fraction, or a signed quantity around zero.
4
4
  *
5
5
  * Only perceptually uniform maps ship, so equal steps in the data look like equal steps.
6
+ *
7
+ * Sequential, low to high:
6
8
  * - `viridis` is the default on the chrome.
7
9
  * - `cividis` is for when the map alone carries the finding and the reader's colour vision is
8
10
  * unknown.
11
+ * - `magma` and `inferno` run from black to a pale yellow through purple and red or orange. They
12
+ * read well over a dark image, where `viridis`' dark end disappears.
13
+ *
14
+ * Diverging, for a signed value whose zero matters (a displacement toward or away from a
15
+ * centre, a difference between two runs):
16
+ * - `blueOrange` runs from a deep blue through a neutral light grey at the middle to a deep
17
+ * orange-brown. Both arms fall in lightness at the same rate and carry the same amount of
18
+ * colour, so +x and -x look equally strong, and its hues avoid the red-green axis. Centre it on zero with `symmetricDomain`.
9
19
  *
10
20
  * A continuous quality is a magnitude even when low values are "good": stepping it onto verdict
11
21
  * colours (green / amber / red) claims a threshold judgement nobody made.
12
22
  *
13
- * The anchors are matplotlib's maps sampled at nine evenly spaced points. Linear interpolation
14
- * between them stays within a few units of the full 256-entry tables.
23
+ * The sequential anchors are the matplotlib maps sampled at nine evenly spaced points. Linear
24
+ * interpolation between them stays within a few units of the full 256-entry tables. The
25
+ * diverging map was constructed in OKLab (equal lightness and chroma steps along each arm,
26
+ * mirrored in lightness, kept inside sRGB) and sampled at seventeen points.
15
27
  */
16
28
 
17
29
  /** The shipped maps. */
18
- export type ColormapName = "viridis" | "cividis";
30
+ export type ColormapName = "viridis" | "cividis" | "magma" | "inferno" | "blueOrange";
19
31
 
20
32
  type Rgb = readonly [number, number, number];
21
33
 
@@ -31,6 +43,47 @@ const ANCHORS: Record<ColormapName, readonly Rgb[]> = {
31
43
  [170, 220, 50],
32
44
  [253, 231, 37],
33
45
  ],
46
+ magma: [
47
+ [0, 0, 4],
48
+ [29, 17, 71],
49
+ [81, 18, 124],
50
+ [131, 38, 129],
51
+ [183, 55, 121],
52
+ [231, 82, 99],
53
+ [252, 137, 97],
54
+ [254, 196, 136],
55
+ [252, 253, 191],
56
+ ],
57
+ inferno: [
58
+ [0, 0, 4],
59
+ [33, 12, 74],
60
+ [87, 16, 110],
61
+ [138, 34, 106],
62
+ [188, 55, 84],
63
+ [228, 90, 49],
64
+ [249, 142, 9],
65
+ [249, 203, 53],
66
+ [252, 255, 164],
67
+ ],
68
+ blueOrange: [
69
+ [0, 70, 140],
70
+ [33, 90, 158],
71
+ [64, 112, 172],
72
+ [92, 133, 185],
73
+ [121, 155, 198],
74
+ [150, 176, 211],
75
+ [179, 198, 222],
76
+ [209, 220, 233],
77
+ [242, 242, 242],
78
+ [230, 216, 207],
79
+ [216, 190, 175],
80
+ [201, 165, 144],
81
+ [186, 140, 113],
82
+ [170, 116, 83],
83
+ [153, 91, 52],
84
+ [136, 67, 13],
85
+ [113, 52, 0],
86
+ ],
34
87
  cividis: [
35
88
  [0, 34, 78],
36
89
  [18, 53, 112],
@@ -45,7 +98,33 @@ const ANCHORS: Record<ColormapName, readonly Rgb[]> = {
45
98
  };
46
99
 
47
100
  /** The names of the shipped maps. */
48
- export const COLORMAPS: readonly ColormapName[] = ["viridis", "cividis"];
101
+ export const COLORMAPS: readonly ColormapName[] = ["viridis", "cividis", "magma", "inferno", "blueOrange"];
102
+
103
+ /** The maps that run through a neutral middle, for a signed value: use them over a domain centred on zero. */
104
+ export const DIVERGING_COLORMAPS: readonly ColormapName[] = ["blueOrange"];
105
+
106
+ /**
107
+ * Whether a map is diverging.
108
+ *
109
+ * @param name - The map.
110
+ * @returns `true` for a map meant for a signed value around zero.
111
+ */
112
+ export function isDivergingColormap(name: ColormapName): boolean {
113
+ return DIVERGING_COLORMAPS.includes(name);
114
+ }
115
+
116
+ /**
117
+ * A domain centred on zero that holds a given one: `[-m, m]` with `m` the largest absolute end.
118
+ * Feed it a diverging map so the middle colour means zero.
119
+ *
120
+ * @param domain - `[low, high]`, or the values to cover.
121
+ * @returns `[-m, m]`; `[-1, 1]` when no end is finite and non-zero.
122
+ */
123
+ export function symmetricDomain(domain: readonly number[]): [number, number] {
124
+ let m = 0;
125
+ for (const v of domain) if (Number.isFinite(v) && Math.abs(v) > m) m = Math.abs(v);
126
+ return m > 0 ? [-m, m] : [-1, 1];
127
+ }
49
128
 
50
129
  /**
51
130
  * The colour of `t` on a map.
@@ -83,6 +162,7 @@ export function colormapRgb(name: ColormapName, t: number): [number, number, num
83
162
  * @param name - The map.
84
163
  * @param value - The value.
85
164
  * @param domain - `[low, high]`: low maps to the map's start. A reversed domain reverses the map.
165
+ * For a diverging map pass a domain centred on zero (`symmetricDomain`).
86
166
  * @returns A CSS colour.
87
167
  */
88
168
  export function colormapValue(name: ColormapName, value: number, domain: readonly [number, number]): string {
package/src/index.ts CHANGED
@@ -22,6 +22,18 @@ export {
22
22
  export { extent, formatTick, histogram, linePath, linearScale, logScale, niceStep, padDomain, type Scale, type Tick } from "./scale";
23
23
 
24
24
  export { LineChart, type LineChartProps, type Series } from "./LineChart";
25
+ export { bandPath, formatWithBand, type SeriesBand } from "./band";
26
+
27
+ export {
28
+ ScatterChart,
29
+ type ScatterChartProps,
30
+ type ScatterColourBy,
31
+ type ScatterPick,
32
+ type ScatterPoint,
33
+ type ScatterReferenceLine,
34
+ type ScatterSeries,
35
+ } from "./ScatterChart";
36
+ export { SCATTER_COLOUR_STEPS, colourDomain, colourStep, nearestProjected } from "./scatter";
25
37
 
26
38
  export { StackedBars, type BarRow, type StackedBarsProps } from "./BarChart";
27
39
 
@@ -43,6 +55,16 @@ export {
43
55
  type ReadoutSeries,
44
56
  } from "./interaction";
45
57
 
46
- export { COLORMAPS, colormap, colormapGradient, colormapRgb, colormapValue, type ColormapName } from "./colormap";
58
+ export {
59
+ COLORMAPS,
60
+ DIVERGING_COLORMAPS,
61
+ colormap,
62
+ colormapGradient,
63
+ colormapRgb,
64
+ colormapValue,
65
+ isDivergingColormap,
66
+ symmetricDomain,
67
+ type ColormapName,
68
+ } from "./colormap";
47
69
 
48
- export { ColormapLegend, type ColormapLegendProps } from "./ColormapLegend";
70
+ export { ColormapLegend, type ColormapClipped, type ColormapLegendProps, type ColormapMarker } from "./ColormapLegend";