@vitavision/charts 0.8.3 → 0.8.5

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/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";
@@ -9,6 +9,8 @@ import { useState } from "react";
9
9
 
10
10
  import { toneColor, type MeasureTone } from "@vitavision/ui";
11
11
 
12
+ import { seriesValueAt } from "./interpolate";
13
+ import { bandValueAt, formatWithBand, type SeriesBand } from "./band";
12
14
  import type { Scale } from "./scale";
13
15
 
14
16
  /** An x range marked on the plot: a gap, a stretch out of tolerance, a region of interest. */
@@ -41,6 +43,8 @@ export interface ReadoutSeries {
41
43
  points: readonly { x: number; y: number }[];
42
44
  /** Its colour. */
43
45
  colour: string;
46
+ /** Its error band: the readout then reads `value ± half-width`, or the value with its range. */
47
+ band?: SeriesBand | undefined;
44
48
  }
45
49
 
46
50
  /** The props `LineChart` and `LineProfile` share for interaction and marking. */
@@ -69,6 +73,8 @@ export interface PlotArea {
69
73
  y1: number;
70
74
  }
71
75
 
76
+ export { seriesValueAt };
77
+
72
78
  /** The ranges behind the series. */
73
79
  export function Bands({ bands, xScale, area }: { bands: readonly Band[]; xScale: Scale; area: PlotArea }) {
74
80
  return (
@@ -117,6 +123,11 @@ export function Markers({ markers, xScale, area }: { markers: readonly Marker[];
117
123
  );
118
124
  }
119
125
 
126
+ /** The default readout format: whole numbers from 100 up, three significant digits below. */
127
+ export function defaultFormat(value: number): string {
128
+ return Math.abs(value) >= 100 ? value.toFixed(0) : value.toPrecision(3);
129
+ }
130
+
120
131
  /**
121
132
  * The pointer layer over the plot area: a crosshair and a value readout while hovering, the
122
133
  * external `cursor` otherwise, and clicks as picks.
@@ -129,7 +140,8 @@ export function PlotInteraction({
129
140
  cursor,
130
141
  onHover,
131
142
  onPick,
132
- format = (value: number) => (Math.abs(value) >= 100 ? value.toFixed(0) : value.toPrecision(3)),
143
+ format = defaultFormat,
144
+ xFormat,
133
145
  }: {
134
146
  xScale: Scale;
135
147
  yScale: Scale;
@@ -139,6 +151,8 @@ export function PlotInteraction({
139
151
  onHover?: ((x: number | null) => void) | undefined;
140
152
  onPick?: ((x: number) => void) | undefined;
141
153
  format?: (value: number) => string;
154
+ /** Formats the x in the readout. Default: `format`. */
155
+ xFormat?: ((value: number) => string) | undefined;
142
156
  }) {
143
157
  const [hover, setHover] = useState<number | null>(null);
144
158
  const interactive = onHover !== undefined || onPick !== undefined;
@@ -164,7 +178,9 @@ export function PlotInteraction({
164
178
  ? []
165
179
  : series.flatMap((entry) => {
166
180
  const y = seriesValueAt(entry.points, hover);
167
- return y === null ? [] : [{ name: entry.name, colour: entry.colour, y }];
181
+ if (y === null) return [];
182
+ const bounds = entry.band ? bandValueAt(entry.points, entry.band, hover) : null;
183
+ return [{ name: entry.name, colour: entry.colour, y, bounds }];
168
184
  });
169
185
 
170
186
  return (
@@ -201,7 +217,10 @@ export function PlotInteraction({
201
217
  fontSize={10}
202
218
  fill="currentColor"
203
219
  >
204
- {[format(hover), ...readout.map((entry) => `${entry.name} ${format(entry.y)}`)].join(" · ")}
220
+ {[
221
+ (xFormat ?? format)(hover),
222
+ ...readout.map((entry) => `${entry.name} ${entry.bounds ? formatWithBand(entry.y, entry.bounds, format) : format(entry.y)}`),
223
+ ].join(" · ")}
205
224
  </text>
206
225
  )}
207
226
  {interactive && (
@@ -229,32 +248,6 @@ export function PlotInteraction({
229
248
  );
230
249
  }
231
250
 
232
- /**
233
- * A series' value at `x`, linearly interpolated between the points either side, or `null`
234
- * outside its range or across a gap.
235
- *
236
- * @param points - The series, in ascending `x`.
237
- * @param x - Where.
238
- * @returns The interpolated value, or `null`.
239
- */
240
- export function seriesValueAt(points: readonly { x: number; y: number }[], x: number): number | null {
241
- if (points.length === 0) return null;
242
- if (points.length === 1) return points[0]!.x === x ? points[0]!.y : null;
243
- let lo = 0;
244
- let hi = points.length - 1;
245
- if (x < points[lo]!.x || x > points[hi]!.x) return null;
246
- while (hi - lo > 1) {
247
- const mid = (lo + hi) >> 1;
248
- if (points[mid]!.x <= x) lo = mid;
249
- else hi = mid;
250
- }
251
- const a = points[lo]!;
252
- const b = points[hi]!;
253
- if (!Number.isFinite(a.y) || !Number.isFinite(b.y)) return null;
254
- if (b.x === a.x) return a.y;
255
- return a.y + ((x - a.x) / (b.x - a.x)) * (b.y - a.y);
256
- }
257
-
258
251
  function clamp(value: number, low: number, high: number): number {
259
252
  return Math.min(high, Math.max(low, value));
260
253
  }
@@ -0,0 +1,27 @@
1
+ /** Reading a series between its points. */
2
+
3
+ /**
4
+ * A series' value at `x`, linearly interpolated between the points either side, or `null`
5
+ * outside its range or across a gap.
6
+ *
7
+ * @param points - The series, in ascending `x`.
8
+ * @param x - Where.
9
+ * @returns The interpolated value, or `null`.
10
+ */
11
+ export function seriesValueAt(points: readonly { x: number; y: number }[], x: number): number | null {
12
+ if (points.length === 0) return null;
13
+ if (points.length === 1) return points[0]!.x === x ? points[0]!.y : null;
14
+ let lo = 0;
15
+ let hi = points.length - 1;
16
+ if (x < points[lo]!.x || x > points[hi]!.x) return null;
17
+ while (hi - lo > 1) {
18
+ const mid = (lo + hi) >> 1;
19
+ if (points[mid]!.x <= x) lo = mid;
20
+ else hi = mid;
21
+ }
22
+ const a = points[lo]!;
23
+ const b = points[hi]!;
24
+ if (!Number.isFinite(a.y) || !Number.isFinite(b.y)) return null;
25
+ if (b.x === a.x) return a.y;
26
+ return a.y + ((x - a.x) / (b.x - a.x)) * (b.y - a.y);
27
+ }
package/src/scatter.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The arithmetic behind `ScatterChart`: which point is under the pointer, which colour step a
3
+ * value falls in, and the domain a colour scale covers.
4
+ *
5
+ * Pure: the component is a thin list of SVG elements over it.
6
+ */
7
+
8
+ import { symmetricDomain } from "./colormap";
9
+
10
+ /** The number of colour steps a value-coloured series is quantised into: one path each. */
11
+ export const SCATTER_COLOUR_STEPS = 24;
12
+
13
+ /**
14
+ * The projected point nearest to a position, within a radius.
15
+ *
16
+ * @param xy - Flat `[x0, y0, x1, y1, …]` in the plot's own units (viewBox units); a non-finite
17
+ * coordinate is skipped.
18
+ * @param x - The query's x.
19
+ * @param y - The query's y.
20
+ * @param radius - How far from a point the query still picks it.
21
+ * @returns The index of the nearest point (the lower index on a tie), or `-1`.
22
+ */
23
+ export function nearestProjected(xy: ArrayLike<number>, x: number, y: number, radius: number): number {
24
+ const limit = radius * radius;
25
+ let best = -1;
26
+ let bestD = Infinity;
27
+ const count = Math.floor(xy.length / 2);
28
+ for (let i = 0; i < count; i++) {
29
+ const dx = xy[2 * i]! - x;
30
+ const dy = xy[2 * i + 1]! - y;
31
+ const d = dx * dx + dy * dy;
32
+ if (d <= limit && d < bestD) {
33
+ best = i;
34
+ bestD = d;
35
+ }
36
+ }
37
+ return best;
38
+ }
39
+
40
+ /**
41
+ * The colour step of a value.
42
+ *
43
+ * @param value - The point's value.
44
+ * @param domain - `[low, high]`: `low` maps to the first step.
45
+ * @param steps - How many steps. Defaults to `SCATTER_COLOUR_STEPS`.
46
+ * @returns An integer in `[0, steps - 1]`; `-1` for a non-finite value; a degenerate domain puts
47
+ * every value in step `0`.
48
+ */
49
+ export function colourStep(value: number, domain: readonly [number, number], steps = SCATTER_COLOUR_STEPS): number {
50
+ if (!Number.isFinite(value)) return -1;
51
+ const [low, high] = domain;
52
+ if (!(high > low)) return 0;
53
+ return Math.min(steps - 1, Math.max(0, Math.floor(((value - low) / (high - low)) * steps)));
54
+ }
55
+
56
+ /**
57
+ * The domain a value colouring covers.
58
+ *
59
+ * @param values - Every point's value; non-finite ones are ignored.
60
+ * @param symmetric - Centre it on zero, for a diverging map.
61
+ * @param given - A domain the caller fixed. It wins, centred if `symmetric`.
62
+ * @returns `[low, high]`; `[0, 1]` when there is no finite value.
63
+ */
64
+ export function colourDomain(values: Iterable<number>, symmetric: boolean, given?: readonly [number, number]): [number, number] {
65
+ let low = Infinity;
66
+ let high = -Infinity;
67
+ if (given) [low, high] = given;
68
+ else {
69
+ for (const v of values) {
70
+ if (!Number.isFinite(v)) continue;
71
+ if (v < low) low = v;
72
+ if (v > high) high = v;
73
+ }
74
+ if (low > high) return symmetric ? [-1, 1] : [0, 1];
75
+ }
76
+ return symmetric ? symmetricDomain([low, high]) : [low, high];
77
+ }