@vitavision/charts 0.8.1 → 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
+ }
@@ -46,14 +46,7 @@ export interface ScoreHistogramProps {
46
46
  * Always the `wide` variant. Painted in the verdict tokens (`--normal`, `--defect`); the
47
47
  * legend names both classes with their counts, so the chart does not rely on colour alone.
48
48
  */
49
- export function ScoreHistogram({
50
- normal,
51
- defect,
52
- threshold,
53
- bins = 32,
54
- label,
55
- className,
56
- }: ScoreHistogramProps) {
49
+ export function ScoreHistogram({ normal, defect, threshold, bins = 32, label, className }: ScoreHistogramProps) {
57
50
  const domain = extent([...normal, ...defect]);
58
51
  const normalBins = histogram(normal, domain, bins);
59
52
  const defectBins = histogram(defect, domain, bins);
@@ -73,24 +66,14 @@ export function ScoreHistogram({
73
66
  footer={
74
67
  <ul className="flex flex-wrap items-center gap-x-4 gap-y-1">
75
68
  <li className="flex items-center gap-1.5">
76
- <span
77
- aria-hidden
78
- className="inline-block h-2 w-3 rounded-sm"
79
- style={{ backgroundColor: NORMAL_FILL, opacity: 0.75 }}
80
- />
69
+ <span aria-hidden className="inline-block h-2 w-3 rounded-sm" style={{ backgroundColor: NORMAL_FILL, opacity: 0.75 }} />
81
70
  <span className="font-mono text-xs">normal ({normal.length})</span>
82
71
  </li>
83
72
  <li className="flex items-center gap-1.5">
84
- <span
85
- aria-hidden
86
- className="inline-block h-2 w-3 rounded-sm"
87
- style={{ backgroundColor: DEFECT_FILL, opacity: 0.75 }}
88
- />
73
+ <span aria-hidden className="inline-block h-2 w-3 rounded-sm" style={{ backgroundColor: DEFECT_FILL, opacity: 0.75 }} />
89
74
  <span className="font-mono text-xs">defect ({defect.length})</span>
90
75
  </li>
91
- {threshold !== undefined && (
92
- <li className="font-mono text-xs">threshold {threshold.toFixed(4)}</li>
93
- )}
76
+ {threshold !== undefined && <li className="font-mono text-xs">threshold {threshold.toFixed(4)}</li>}
94
77
  </ul>
95
78
  }
96
79
  >
@@ -9,16 +9,5 @@ import type { Scale } from "./scale";
9
9
  export function ThresholdRule({ value, xScale, area }: { value: number | undefined; xScale: Scale; area: PlotArea }) {
10
10
  if (value === undefined || !Number.isFinite(value)) return null;
11
11
  const x = xScale.project(value);
12
- return (
13
- <line
14
- data-threshold=""
15
- x1={x}
16
- x2={x}
17
- y1={area.y0}
18
- y2={area.y1}
19
- stroke="currentColor"
20
- strokeWidth={1.25}
21
- strokeDasharray="3 2"
22
- />
23
- );
12
+ return <line data-threshold="" x1={x} x2={x} y1={area.y0} y2={area.y1} stroke="currentColor" strokeWidth={1.25} strokeDasharray="3 2" />;
24
13
  }
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/bars.ts CHANGED
@@ -34,11 +34,7 @@ function usableDomain(low: number, high: number): [number, number] {
34
34
  * widened so it lands in a middle bin rather than on an edge.
35
35
  * @returns The counts and the domain they span.
36
36
  */
37
- export function binValues(
38
- values: ArrayLike<number>,
39
- bins: number | undefined,
40
- domain?: [number, number],
41
- ): BinnedData {
37
+ export function binValues(values: ArrayLike<number>, bins: number | undefined, domain?: [number, number]): BinnedData {
42
38
  const count = bins === undefined ? DEFAULT_BINS : Number.isFinite(bins) ? Math.max(1, Math.floor(bins)) : 1;
43
39
  const finite: number[] = [];
44
40
  for (let index = 0; index < values.length; index += 1) {