@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.
@@ -4,7 +4,19 @@
4
4
 
5
5
  import { cn } from "@vitavision/ui";
6
6
 
7
- import { colormapGradient, type ColormapName } from "./colormap";
7
+ import { colormap, colormapGradient, symmetricDomain, type ColormapName } from "./colormap";
8
+ import { linearScale } from "./scale";
9
+
10
+ /** A value marked on a {@link ColormapLegend}: a threshold, a cursor value, a reference. */
11
+ export interface ColormapMarker {
12
+ /** Where, in the legend's value units. A value outside the domain is left out. */
13
+ value: number;
14
+ /** The marker's text. Default: the value, formatted with the legend's `format` and `unit`. */
15
+ label?: string | undefined;
16
+ }
17
+
18
+ /** Which end of a {@link ColormapLegend} the data runs past: `"high"` is `≥ max`, `"low"` is `≤ min`. */
19
+ export type ColormapClipped = "high" | "low" | "both";
8
20
 
9
21
  /** Props of `ColormapLegend`. */
10
22
  export interface ColormapLegendProps {
@@ -16,31 +28,258 @@ export interface ColormapLegendProps {
16
28
  unit?: string | undefined;
17
29
  /** What the colour encodes, written before the bar ("Validity", "Edge error"). */
18
30
  label: string;
19
- /** Formats the end values. Defaults to at most 3 significant figures, without trailing zeros. */
31
+ /** Formats the end and tick values. Defaults to at most 3 significant figures, without trailing zeros. */
20
32
  format?: ((value: number) => string) | undefined;
21
- /** Merged onto the row with `cn`. */
33
+ /**
34
+ * How the bar runs. `horizontal` (the default) is one line, low to high; `vertical` is a
35
+ * column with the label above and the high end at the top, for the side of a map.
36
+ */
37
+ orientation?: "horizontal" | "vertical" | undefined;
38
+ /**
39
+ * Values to label along the bar: a list, or a rough count of round ones. Without it a
40
+ * `horizontal` legend labels its two ends in line with the bar and a `vertical` one labels
41
+ * its two ends (and zero, when `symmetric`). With it the values sit along the bar, at their
42
+ * position on the map; values outside `domain` are left out. A count also labels the two ends.
43
+ */
44
+ ticks?: number | readonly number[] | undefined;
45
+ /**
46
+ * Centre the scale on zero for a diverging map: `domain` is widened to `[-m, m]` with `m`
47
+ * its largest absolute end, so the middle colour is zero and the middle tick says so.
48
+ */
49
+ symmetric?: boolean | undefined;
50
+ /**
51
+ * Values to mark on the bar: a number, a `{ value, label? }`, or a list of either. Each is a
52
+ * tick across the bar with its text beside it (above a horizontal bar, to the right of the
53
+ * ticks on a vertical one): the label, or else the value with the unit. The text carries the
54
+ * meaning; the tick is decorative. A value outside `domain` is left out.
55
+ */
56
+ marker?: number | ColormapMarker | readonly (number | ColormapMarker)[] | undefined;
57
+ /**
58
+ * The scale saturates: the data runs past the end of `domain`. The end gets a cap (a small
59
+ * arrow in the end colour) and its value reads `≥ max` (`high`) or `≤ min` (`low`); `both`
60
+ * does both ends. The end value is labelled even when `ticks` leaves it out.
61
+ */
62
+ clipped?: ColormapClipped | undefined;
63
+ /** For `vertical`: the bar's length in CSS pixels. Defaults to 160. */
64
+ length?: number | undefined;
65
+ /** Merged onto the legend with `cn`. */
22
66
  className?: string | undefined;
23
67
  }
24
68
 
69
+ const defaultFormat = (value: number) => String(Number(value.toPrecision(3)));
70
+
71
+ /** The tick values: a given list inside the domain, or round values, or the default for the layout. */
72
+ function tickValues(ticks: ColormapLegendProps["ticks"], domain: readonly [number, number], symmetric: boolean): number[] {
73
+ const [low, high] = domain;
74
+ const inside = (v: number) => Number.isFinite(v) && v >= Math.min(low, high) - 1e-12 && v <= Math.max(low, high) + 1e-12;
75
+ if (typeof ticks === "number") {
76
+ // Round values, and the two ends: a scale is read from its ends. A round value within 8 % of an end gives way to it.
77
+ const span = Math.abs(high - low);
78
+ const round = linearScale([low, high], 0, 1)
79
+ .ticks(ticks)
80
+ .map((tick) => tick.value)
81
+ .filter((v) => inside(v) && Math.abs(v - low) > 0.08 * span && Math.abs(v - high) > 0.08 * span);
82
+ return [low, ...round, high];
83
+ }
84
+ if (ticks !== undefined) return ticks.filter(inside);
85
+ return symmetric ? [low, 0, high] : [low, high];
86
+ }
87
+
88
+ /** `marker` as a list of `{ value, label }`, in domain, in the order given. */
89
+ function markerList(marker: ColormapLegendProps["marker"], low: number, high: number): ColormapMarker[] {
90
+ if (marker === undefined) return [];
91
+ const list =
92
+ typeof marker === "number" || !Array.isArray(marker)
93
+ ? [marker as number | ColormapMarker]
94
+ : [...(marker as readonly (number | ColormapMarker)[])];
95
+ const lo = Math.min(low, high) - 1e-12;
96
+ const hi = Math.max(low, high) + 1e-12;
97
+ return list
98
+ .map((entry) => (typeof entry === "number" ? { value: entry } : entry))
99
+ .filter((entry) => Number.isFinite(entry.value) && entry.value >= lo && entry.value <= hi);
100
+ }
101
+
102
+ /** The cap on a clipped end: an arrow in the map's end colour, pointing outward. */
103
+ function EndCap({ map, end, orientation }: { map: ColormapName; end: "low" | "high"; orientation: "horizontal" | "vertical" }) {
104
+ const horizontal = orientation === "horizontal";
105
+ const clip = horizontal
106
+ ? end === "high"
107
+ ? "polygon(0 0, 100% 50%, 0 100%)"
108
+ : "polygon(100% 0, 0 50%, 100% 100%)"
109
+ : end === "high"
110
+ ? "polygon(50% 0, 100% 100%, 0 100%)"
111
+ : "polygon(0 0, 100% 0, 50% 100%)";
112
+ const place = horizontal
113
+ ? end === "high"
114
+ ? "left-full top-0.5 ml-px h-2 w-1.5"
115
+ : "right-full top-0.5 mr-px h-2 w-1.5"
116
+ : end === "high"
117
+ ? "bottom-full left-0 mb-px h-1.5 w-2.5"
118
+ : "top-full left-0 mt-px h-1.5 w-2.5";
119
+ return (
120
+ <span
121
+ aria-hidden
122
+ data-cap={end}
123
+ className={`absolute ${place}`}
124
+ style={{ backgroundColor: colormap(map, end === "high" ? 1 : 0), clipPath: clip }}
125
+ />
126
+ );
127
+ }
128
+
25
129
  /**
26
- * A gradient bar with its end values and unit, read as one line: "Edge error 0 [bar] 2.5 px".
27
- * The bar is decorative; the label and the end values carry the meaning as text.
130
+ * A gradient bar with its values and unit.
131
+ *
132
+ * - **Horizontal**: one line, "Edge error 0 [bar] 2.5 px". With `ticks` or `symmetric` the values
133
+ * sit under the bar at their position instead.
134
+ * - **Vertical**: the label above a column bar, the high end at the top, the values beside the
135
+ * bar at their position, and the unit after the label.
136
+ *
137
+ * `marker` ticks values on the bar (a threshold, the value under a cursor) and `clipped` says
138
+ * the scale saturates at an end, with a cap and `≥` / `≤` on its value.
139
+ *
140
+ * The bar is decorative; the label, the values and the markers' text carry the meaning.
28
141
  */
29
142
  export function ColormapLegend({
30
143
  map,
31
144
  domain,
32
145
  unit,
33
146
  label,
34
- format = (value) => String(Number(value.toPrecision(3))),
147
+ format = defaultFormat,
148
+ orientation = "horizontal",
149
+ ticks,
150
+ symmetric = false,
151
+ marker,
152
+ clipped,
153
+ length = 160,
35
154
  className,
36
155
  }: ColormapLegendProps) {
156
+ const [low, high] = symmetric ? symmetricDomain(domain) : domain;
157
+ const span = high - low;
37
158
  const end = (value: number) => (unit ? `${format(value)} ${unit}` : format(value));
159
+ const fraction = (value: number) => (span === 0 ? 0 : (value - low) / span);
160
+ const markers = markerList(marker, low, high);
161
+ const capLow = clipped === "low" || clipped === "both";
162
+ const capHigh = clipped === "high" || clipped === "both";
163
+ // `≤ min` / `≥ max` on the clipped end's text. Where `low` and `high` coincide the high end wins.
164
+ const text = (value: number, isLow: boolean, isHigh: boolean) =>
165
+ `${isHigh && capHigh ? "≥ " : isLow && capLow ? "≤ " : ""}${format(value)}`;
166
+ const markerText = (entry: ColormapMarker) => entry.label ?? end(entry.value);
167
+
168
+ if (orientation === "horizontal" && ticks === undefined && !symmetric && markers.length === 0) {
169
+ return (
170
+ <div className={cn("flex items-center gap-2 text-xs text-fg-muted", className)} data-colormap={map}>
171
+ <span>{label}</span>
172
+ <span className="font-mono tabular-nums">{capLow ? `≤ ${end(low)}` : end(low)}</span>
173
+ <span aria-hidden className="relative h-2 w-24 rounded-full" style={{ backgroundImage: colormapGradient(map) }}>
174
+ {capLow && <EndCap map={map} end="low" orientation="horizontal" />}
175
+ {capHigh && <EndCap map={map} end="high" orientation="horizontal" />}
176
+ </span>
177
+ <span className="font-mono tabular-nums">{capHigh ? `≥ ${end(high)}` : end(high)}</span>
178
+ </div>
179
+ );
180
+ }
181
+
182
+ const values = tickValues(ticks, [low, high], symmetric);
183
+ // A clipped end is always labelled, even when a given `ticks` list leaves it out.
184
+ if (capLow && !values.includes(low)) values.unshift(low);
185
+ if (capHigh && !values.includes(high)) values.push(high);
186
+ const tickText = (value: number) => text(value, value === low, value === high);
187
+
188
+ if (orientation === "horizontal") {
189
+ return (
190
+ <div className={cn("flex items-start gap-2 text-xs text-fg-muted", className)} data-colormap={map}>
191
+ <span className={markers.length > 0 ? "pt-4" : undefined}>{label}</span>
192
+ {/* The values are positioned against the bar; `pb-4` leaves the row room for them, `pt-4` the markers' text. */}
193
+ <div className={cn("relative w-32 pb-4", markers.length > 0 && "pt-4", (capLow || capHigh) && "mx-2")}>
194
+ <div className="relative mt-0.5 h-2">
195
+ <div aria-hidden className="absolute inset-0 rounded-full" style={{ backgroundImage: colormapGradient(map) }} />
196
+ {capLow && <EndCap map={map} end="low" orientation="horizontal" />}
197
+ {capHigh && <EndCap map={map} end="high" orientation="horizontal" />}
198
+ {markers.map((entry) => (
199
+ <span
200
+ key={`m-${entry.value}-${entry.label ?? ""}`}
201
+ aria-hidden
202
+ data-marker-tick=""
203
+ className="absolute -top-0.5 h-3 w-0.5 -translate-x-1/2 rounded-full bg-fg ring-1 ring-surface"
204
+ style={{ left: `${(fraction(entry.value) * 100).toFixed(2)}%` }}
205
+ />
206
+ ))}
207
+ </div>
208
+ {markers.map((entry) => (
209
+ <span
210
+ key={`mt-${entry.value}-${entry.label ?? ""}`}
211
+ data-marker=""
212
+ className="absolute top-0 -translate-x-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums text-fg"
213
+ style={{ left: `${(fraction(entry.value) * 100).toFixed(2)}%` }}
214
+ >
215
+ {markerText(entry)}
216
+ </span>
217
+ ))}
218
+ {values.map((value) => (
219
+ <span
220
+ key={value}
221
+ data-tick=""
222
+ className={cn("absolute -translate-x-1/2 font-mono text-[10px] tabular-nums", markers.length > 0 ? "top-7" : "top-3")}
223
+ style={{ left: `${(fraction(value) * 100).toFixed(2)}%` }}
224
+ >
225
+ {tickText(value)}
226
+ </span>
227
+ ))}
228
+ </div>
229
+ {unit && <span className={cn("text-fg-subtle", markers.length > 0 && "pt-4")}>{unit}</span>}
230
+ </div>
231
+ );
232
+ }
233
+
38
234
  return (
39
- <div className={cn("flex items-center gap-2 text-xs text-fg-muted", className)} data-colormap={map}>
40
- <span>{label}</span>
41
- <span className="font-mono tabular-nums">{end(domain[0])}</span>
42
- <span aria-hidden className="h-2 w-24 rounded-full" style={{ backgroundImage: colormapGradient(map) }} />
43
- <span className="font-mono tabular-nums">{end(domain[1])}</span>
235
+ <div className={cn("inline-flex flex-col gap-1.5 text-xs text-fg-muted", className)} data-colormap={map} data-orientation="vertical">
236
+ <span>
237
+ {label}
238
+ {unit && <span className="ml-1 text-fg-subtle">{unit}</span>}
239
+ </span>
240
+ {/* The values sit on the bar's right; the margin above and below keeps the end values inside the box. */}
241
+ <div className="relative my-1.5 flex" style={{ height: length }}>
242
+ <div className="relative w-2.5">
243
+ <div aria-hidden className="absolute inset-0 rounded-full" style={{ backgroundImage: colormapGradient(map, "to top") }} />
244
+ {capLow && <EndCap map={map} end="low" orientation="vertical" />}
245
+ {capHigh && <EndCap map={map} end="high" orientation="vertical" />}
246
+ {markers.map((entry) => (
247
+ <span
248
+ key={`m-${entry.value}-${entry.label ?? ""}`}
249
+ aria-hidden
250
+ data-marker-tick=""
251
+ className="absolute -left-0.5 -right-0.5 h-0.5 translate-y-1/2 rounded-full bg-fg ring-1 ring-surface"
252
+ style={{ bottom: `${(fraction(entry.value) * 100).toFixed(2)}%` }}
253
+ />
254
+ ))}
255
+ </div>
256
+ <div className="relative ml-1.5 min-w-8">
257
+ {values.map((value) => (
258
+ <span
259
+ key={value}
260
+ data-tick=""
261
+ className="absolute left-0 translate-y-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums"
262
+ style={{ bottom: `${(fraction(value) * 100).toFixed(2)}%` }}
263
+ >
264
+ {tickText(value)}
265
+ </span>
266
+ ))}
267
+ </div>
268
+ {markers.length > 0 && (
269
+ <div className="relative ml-1.5 min-w-8">
270
+ {markers.map((entry) => (
271
+ <span
272
+ key={`mt-${entry.value}-${entry.label ?? ""}`}
273
+ data-marker=""
274
+ className="absolute left-0 translate-y-1/2 whitespace-nowrap font-mono text-[10px] leading-none tabular-nums text-fg"
275
+ style={{ bottom: `${(fraction(entry.value) * 100).toFixed(2)}%` }}
276
+ >
277
+ {markerText(entry)}
278
+ </span>
279
+ ))}
280
+ </div>
281
+ )}
282
+ </div>
44
283
  </div>
45
284
  );
46
285
  }
package/src/Frame.tsx CHANGED
@@ -109,6 +109,8 @@ export interface FrameProps {
109
109
  xTicks?: number;
110
110
  /** Rough number of y ticks to ask the scale for. Default 4. */
111
111
  yTicks?: number;
112
+ /** Writes an x tick's label from its value (a date, a unit). Omitted: the scale's own label. */
113
+ xFormat?: ((value: number) => string) | undefined;
112
114
  /** Drawn inside the plot area, above the grid and below nothing. */
113
115
  children?: ReactNode;
114
116
  /** Accessible name — every chart must have one; it is what the tests query on. */
@@ -139,6 +141,7 @@ export function Frame({
139
141
  yLabel,
140
142
  xTicks = 5,
141
143
  yTicks = 4,
144
+ xFormat,
142
145
  children,
143
146
  label,
144
147
  footer,
@@ -173,7 +176,7 @@ export function Frame({
173
176
  <g key={`x-${tick.value}`}>
174
177
  <line x1={x} x2={x} y1={plotArea.y0} y2={plotArea.y1} stroke={AXIS} strokeWidth={0.5} opacity={0.15} />
175
178
  <text x={x} y={plotArea.y0 + 14} textAnchor="middle" fontSize={10} fill={AXIS}>
176
- {tick.label}
179
+ {xFormat ? xFormat(tick.value) : tick.label}
177
180
  </text>
178
181
  </g>
179
182
  );
@@ -206,6 +209,8 @@ export interface LegendItem {
206
209
  label: string;
207
210
  /** Any CSS colour: a `var(--series-n)` from {@link seriesColour}, or a verdict token. */
208
211
  colour: string;
212
+ /** The series has an error band: its swatch shows one, and this text follows the name (`±1σ`). */
213
+ band?: string | undefined;
209
214
  }
210
215
 
211
216
  /** Props for {@link Legend}. */
@@ -229,8 +234,16 @@ export function Legend({ items, className }: LegendProps) {
229
234
  <ul className={cn("flex flex-wrap items-center gap-x-4 gap-y-1", className)}>
230
235
  {items.map((item) => (
231
236
  <li key={item.label} className="flex items-center gap-1.5">
232
- <span aria-hidden className="inline-block h-0.5 w-4 rounded-full" style={{ backgroundColor: item.colour }} />
237
+ {item.band === undefined ? (
238
+ <span aria-hidden className="inline-block h-0.5 w-4 rounded-full" style={{ backgroundColor: item.colour }} />
239
+ ) : (
240
+ <span aria-hidden data-band-swatch="" className="relative inline-block h-2.5 w-4">
241
+ <span className="absolute inset-0 rounded-sm opacity-20" style={{ backgroundColor: item.colour }} />
242
+ <span className="absolute inset-x-0 top-1/2 h-0.5 -translate-y-1/2 rounded-full" style={{ backgroundColor: item.colour }} />
243
+ </span>
244
+ )}
233
245
  <span className="font-mono text-xs">{item.label}</span>
246
+ {item.band !== undefined && <span className="font-mono text-xs text-fg-subtle">{item.band}</span>}
234
247
  </li>
235
248
  ))}
236
249
  </ul>
package/src/LineChart.tsx CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { ReactNode } from "react";
11
11
 
12
+ import { bandPath, bandValues, type SeriesBand } from "./band";
12
13
  import { FLUID_DEFAULT_HEIGHT, Frame, Legend, areaFor, seriesColour, useFluidSize } from "./Frame";
13
14
  import { Bands, Markers, PlotInteraction, type InteractionProps } from "./interaction";
14
15
  import type { Variant } from "./Frame";
@@ -26,6 +27,15 @@ export interface Series {
26
27
  points: { x: number; y: number }[];
27
28
  /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. */
28
29
  colour?: string;
30
+ /**
31
+ * An error band around the line: `lower` and `upper` hold one value per point, by index (a
32
+ * mean ± σ, a confidence interval). It is drawn as a translucent area in the series colour
33
+ * under every line, shown in the legend, and read in the hover readout as `value ± half-width`
34
+ * (or the value with its range when the band is not symmetric). A point whose edges are
35
+ * missing or non-finite leaves a gap in the band. Unless `yDomain` is fixed, the y domain
36
+ * grows to hold the band.
37
+ */
38
+ band?: SeriesBand;
29
39
  }
30
40
 
31
41
  /** Props for {@link LineChart}. */
@@ -42,7 +52,12 @@ export interface LineChartProps extends InteractionProps {
42
52
  logY?: boolean;
43
53
  /** Fixed domains, for charts whose axes are known — ROC and PR are both `[0, 1]`. */
44
54
  xDomain?: [number, number];
45
- /** Fixed y domain. Omitted: the extent of every series' `y`. */
55
+ /**
56
+ * Writes the x tick labels and the x in the hover readout from the x value: a date from a
57
+ * timestamp, a unit. Omitted: the scale's own labels.
58
+ */
59
+ xFormat?: (x: number) => string;
60
+ /** Fixed y domain. Omitted: the extent of every series' `y` and band edges. */
46
61
  yDomain?: [number, number];
47
62
  /** Drawn behind the series, in plot pixels. A chance diagonal or a tolerance band uses this. */
48
63
  underlay?: (x: Scale, y: Scale) => ReactNode;
@@ -65,7 +80,8 @@ export interface LineChartProps extends InteractionProps {
65
80
  * An SVG `role="img"` named by `label`, with the legend as real text under it. Series are
66
81
  * told apart by the legend's names, never by colour alone. `bands` and `markers` mark x
67
82
  * ranges and positions; `onHover` adds a crosshair and a value readout, `onPick` makes a
68
- * click report its x, and `cursor` draws an x chosen elsewhere.
83
+ * click report its x, and `cursor` draws an x chosen elsewhere. A series' `band` adds an error
84
+ * band, and `xFormat` writes the x labels.
69
85
  */
70
86
  export function LineChart({
71
87
  series,
@@ -75,6 +91,7 @@ export function LineChart({
75
91
  logY = false,
76
92
  xDomain,
77
93
  yDomain,
94
+ xFormat,
78
95
  underlay,
79
96
  footer,
80
97
  showLegend = true,
@@ -88,7 +105,7 @@ export function LineChart({
88
105
  onPick,
89
106
  }: LineChartProps) {
90
107
  const allX = series.flatMap((entry) => entry.points.map((point) => point.x));
91
- const allY = series.flatMap((entry) => entry.points.map((point) => point.y));
108
+ const allY = series.flatMap((entry) => [...entry.points.map((point) => point.y), ...(entry.band ? bandValues(entry.band) : [])]);
92
109
  const [fluidRef, fluidSize] = useFluidSize(height);
93
110
  const size = variant === "fluid" ? fluidSize : undefined;
94
111
  const plotArea = areaFor(variant, size);
@@ -113,14 +130,37 @@ export function LineChart({
113
130
  className={className}
114
131
  size={size}
115
132
  figureRef={variant === "fluid" ? fluidRef : undefined}
133
+ xFormat={xFormat}
116
134
  footer={
117
135
  <div className="flex flex-col gap-1">
118
- {showLegend && <Legend items={coloured.map((entry) => ({ label: entry.name, colour: entry.colour }))} />}
136
+ {showLegend && (
137
+ <Legend
138
+ items={coloured.map((entry) => ({
139
+ label: entry.name,
140
+ colour: entry.colour,
141
+ ...(entry.band ? { band: entry.band.label ?? "± band" } : {}),
142
+ }))}
143
+ />
144
+ )}
119
145
  {footer}
120
146
  </div>
121
147
  }
122
148
  >
123
149
  {bands && bands.length > 0 && <Bands bands={bands} xScale={xScale} area={plotArea} />}
150
+ {coloured.map(
151
+ (entry) =>
152
+ entry.band && (
153
+ <path
154
+ key={`band-${entry.name}`}
155
+ data-series-band={entry.name}
156
+ aria-hidden
157
+ d={bandPath(entry.points, entry.band, xScale, yScale)}
158
+ fill={entry.colour}
159
+ fillOpacity={0.16}
160
+ stroke="none"
161
+ />
162
+ ),
163
+ )}
124
164
  {underlay?.(xScale, yScale)}
125
165
  {coloured.map((entry) =>
126
166
  entry.points.length === 1 ? (
@@ -153,6 +193,7 @@ export function LineChart({
153
193
  cursor={cursor}
154
194
  onHover={onHover}
155
195
  onPick={onPick}
196
+ xFormat={xFormat}
156
197
  />
157
198
  )}
158
199
  </Frame>