@vitavision/charts 0.6.0

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,132 @@
1
+ /**
2
+ * Score distribution by class, with a threshold drawn on it.
3
+ *
4
+ * This is the chart that makes a threshold decision legible: a confusion matrix says how
5
+ * many were wrong, and this says *why* — two distributions that barely separate, or one
6
+ * long normal tail crossing the line.
7
+ *
8
+ * Both classes share one set of bin edges, computed over the union of their scores. Binned
9
+ * separately they would be drawn on different axes and the overlap — the only thing worth
10
+ * looking at — would be an artefact of the binning.
11
+ */
12
+
13
+ import { DEFECT_COLOUR, Frame, NORMAL_COLOUR, areaFor } from "./Frame";
14
+ import { extent, histogram, linearScale } from "./scale";
15
+
16
+ // The histogram is always given a whole panel, never a column of a grid.
17
+ const plotArea = areaFor("wide");
18
+
19
+ // Green for normal, red for defect — the verdict tokens, named once in `Frame`.
20
+ const NORMAL_FILL = NORMAL_COLOUR;
21
+ const DEFECT_FILL = DEFECT_COLOUR;
22
+
23
+ /** Props for {@link ScoreHistogram}. */
24
+ export interface HistogramProps {
25
+ /** Anomaly scores of the samples labelled normal. */
26
+ normal: number[];
27
+ /** Anomaly scores of the samples labelled defective. */
28
+ defect: number[];
29
+ /** The decision threshold, drawn as a dashed vertical rule. Omitted or non-finite: none. */
30
+ threshold?: number;
31
+ /** Number of equal-width bins over the union of both classes' scores. Default 32. */
32
+ bins?: number;
33
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
34
+ label: string;
35
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
36
+ className?: string | undefined;
37
+ }
38
+
39
+ /**
40
+ * Overlaid histograms of the normal and defect score distributions, with the threshold on
41
+ * them.
42
+ *
43
+ * @remarks
44
+ * Always the `wide` variant. Painted in the verdict tokens (`--normal`, `--defect`); the
45
+ * legend names both classes with their counts, so the chart does not rely on colour alone.
46
+ */
47
+ export function ScoreHistogram({
48
+ normal,
49
+ defect,
50
+ threshold,
51
+ bins = 32,
52
+ label,
53
+ className,
54
+ }: HistogramProps) {
55
+ const domain = extent([...normal, ...defect]);
56
+ const normalBins = histogram(normal, domain, bins);
57
+ const defectBins = histogram(defect, domain, bins);
58
+ const tallest = Math.max(1, ...normalBins, ...defectBins);
59
+
60
+ const xScale = linearScale(domain, plotArea.x0, plotArea.x1);
61
+ const yScale = linearScale([0, tallest], plotArea.y0, plotArea.y1);
62
+ const binWidth = (plotArea.x1 - plotArea.x0) / bins;
63
+
64
+ const bars = (counts: number[], fill: string, opacity: number) =>
65
+ counts
66
+ .map((count, index) => ({ count, x: plotArea.x0 + index * binWidth }))
67
+ .map(({ count, x }) =>
68
+ count === 0 ? null : (
69
+ <rect
70
+ key={`${fill}-${x}`}
71
+ x={x}
72
+ y={yScale.project(count)}
73
+ width={Math.max(0.5, binWidth - 0.5)}
74
+ height={plotArea.y0 - yScale.project(count)}
75
+ fill={fill}
76
+ opacity={opacity}
77
+ />
78
+ ),
79
+ );
80
+
81
+ return (
82
+ <Frame
83
+ xScale={xScale}
84
+ yScale={yScale}
85
+ xLabel="anomaly score"
86
+ yLabel="samples"
87
+ label={label}
88
+ variant="wide"
89
+ className={className}
90
+ footer={
91
+ <ul className="flex flex-wrap items-center gap-x-4 gap-y-1">
92
+ <li className="flex items-center gap-1.5">
93
+ <span
94
+ aria-hidden
95
+ className="inline-block h-2 w-3 rounded-sm"
96
+ style={{ backgroundColor: NORMAL_FILL, opacity: 0.75 }}
97
+ />
98
+ <span className="font-mono text-xs">normal ({normal.length})</span>
99
+ </li>
100
+ <li className="flex items-center gap-1.5">
101
+ <span
102
+ aria-hidden
103
+ className="inline-block h-2 w-3 rounded-sm"
104
+ style={{ backgroundColor: DEFECT_FILL, opacity: 0.75 }}
105
+ />
106
+ <span className="font-mono text-xs">defect ({defect.length})</span>
107
+ </li>
108
+ {threshold !== undefined && (
109
+ <li className="font-mono text-xs">threshold {threshold.toFixed(4)}</li>
110
+ )}
111
+ </ul>
112
+ }
113
+ >
114
+ {/* Normals first and defects over them: the defect bars are the smaller population
115
+ in every realistic split, so drawing them last keeps them from being buried. */}
116
+ {bars(normalBins, NORMAL_FILL, 0.65)}
117
+ {bars(defectBins, DEFECT_FILL, 0.65)}
118
+
119
+ {threshold !== undefined && Number.isFinite(threshold) && (
120
+ <line
121
+ x1={xScale.project(threshold)}
122
+ x2={xScale.project(threshold)}
123
+ y1={plotArea.y0}
124
+ y2={plotArea.y1}
125
+ stroke="currentColor"
126
+ strokeWidth={1.25}
127
+ strokeDasharray="3 2"
128
+ />
129
+ )}
130
+ </Frame>
131
+ );
132
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Multi-series line chart — training curves, or any series plotted over a shared axis.
3
+ *
4
+ * A series with no points draws nothing but still claims its legend entry, so a term that
5
+ * has not reported yet is visibly pending rather than silently absent. A series with one
6
+ * point draws a dot: at the start of a run that is genuinely all there is, and an empty
7
+ * chart would read as "nothing is happening".
8
+ */
9
+
10
+ import type { ReactNode } from "react";
11
+
12
+ import { Frame, Legend, areaFor, seriesColour } from "./Frame";
13
+ import type { Variant } from "./Frame";
14
+ import type { Scale } from "./scale";
15
+ import { extent, linePath, linearScale, logScale } from "./scale";
16
+
17
+ /** One line of a {@link LineChart}. */
18
+ export interface Series {
19
+ /** Legend text, and the React key — unique within one chart. */
20
+ name: string;
21
+ /**
22
+ * Points in draw order. A non-finite coordinate lifts the pen rather than bridging the
23
+ * gap; a single point draws a dot; no points draws nothing but keeps the legend entry.
24
+ */
25
+ points: { x: number; y: number }[];
26
+ /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. */
27
+ colour?: string;
28
+ }
29
+
30
+ /** Props for {@link LineChart}. */
31
+ export interface LineChartProps {
32
+ /** The lines, drawn in order — a later series paints over an earlier one. */
33
+ series: Series[];
34
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
35
+ label: string;
36
+ /** x-axis title. */
37
+ xLabel?: string;
38
+ /** y-axis title. */
39
+ yLabel?: string;
40
+ /** Losses span decades; a linear axis flattens two of the three onto the floor. */
41
+ logY?: boolean;
42
+ /** Fixed domains, for charts whose axes are known — ROC and PR are both `[0, 1]`. */
43
+ xDomain?: [number, number];
44
+ /** Fixed y domain. Omitted: the extent of every series' `y`. */
45
+ yDomain?: [number, number];
46
+ /** Drawn behind the series, in plot pixels. A chance diagonal or a tolerance band uses this. */
47
+ underlay?: (x: Scale, y: Scale) => ReactNode;
48
+ /** Rendered under the legend, inside the `<figcaption>`. */
49
+ footer?: ReactNode;
50
+ /** Show the legend row. Default `true`. */
51
+ showLegend?: boolean;
52
+ /** Where the chart is going (see {@link Variant}). Default `"panel"`. */
53
+ variant?: Variant;
54
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
55
+ className?: string | undefined;
56
+ }
57
+
58
+ /**
59
+ * A multi-series line chart over a shared x axis — training curves, ROC and PR curves.
60
+ *
61
+ * @remarks
62
+ * An SVG `role="img"` named by `label`, with the legend as real text under it. Series are
63
+ * told apart by the legend's names, never by colour alone.
64
+ */
65
+ export function LineChart({
66
+ series,
67
+ label,
68
+ xLabel,
69
+ yLabel,
70
+ logY = false,
71
+ xDomain,
72
+ yDomain,
73
+ underlay,
74
+ footer,
75
+ showLegend = true,
76
+ variant = "panel",
77
+ className,
78
+ }: LineChartProps) {
79
+ const allX = series.flatMap((entry) => entry.points.map((point) => point.x));
80
+ const allY = series.flatMap((entry) => entry.points.map((point) => point.y));
81
+ const plotArea = areaFor(variant);
82
+
83
+ const xScale = linearScale(xDomain ?? extent(allX), plotArea.x0, plotArea.x1);
84
+ const makeY = logY ? logScale : linearScale;
85
+ const yScale = makeY(yDomain ?? extent(allY), plotArea.y0, plotArea.y1);
86
+
87
+ const coloured = series.map((entry, index) => ({
88
+ ...entry,
89
+ colour: entry.colour ?? seriesColour(index),
90
+ }));
91
+
92
+ return (
93
+ <Frame
94
+ xScale={xScale}
95
+ yScale={yScale}
96
+ xLabel={xLabel}
97
+ yLabel={yLabel}
98
+ label={label}
99
+ variant={variant}
100
+ className={className}
101
+ footer={
102
+ <div className="flex flex-col gap-1">
103
+ {showLegend && (
104
+ <Legend
105
+ items={coloured.map((entry) => ({ label: entry.name, colour: entry.colour }))}
106
+ />
107
+ )}
108
+ {footer}
109
+ </div>
110
+ }
111
+ >
112
+ {underlay?.(xScale, yScale)}
113
+ {coloured.map((entry) =>
114
+ entry.points.length === 1 ? (
115
+ <circle
116
+ key={entry.name}
117
+ cx={xScale.project(entry.points[0]?.x ?? 0)}
118
+ cy={yScale.project(entry.points[0]?.y ?? 0)}
119
+ r={2.5}
120
+ fill={entry.colour}
121
+ />
122
+ ) : (
123
+ <path
124
+ key={entry.name}
125
+ d={linePath(entry.points, xScale, yScale)}
126
+ fill="none"
127
+ stroke={entry.colour}
128
+ strokeWidth={1.5}
129
+ strokeLinejoin="round"
130
+ vectorEffect="non-scaling-stroke"
131
+ />
132
+ ),
133
+ )}
134
+ </Frame>
135
+ );
136
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * A 1-D profile chart — intensity or value against arc length along a scan line or a
3
+ * caliper axis.
4
+ *
5
+ * Built on the same `Frame` and `scale.ts` every other chart here uses, so a profile reads
6
+ * as part of the same visual system as a training curve or a score histogram rather than a
7
+ * one-off. The one thing a profile chart needs that a loss curve does not is a way to mark
8
+ * *where along x a decision landed* — a detected edge, a caliper's chosen crossing — as a
9
+ * vertical rule with its own label, independent of the series being plotted.
10
+ */
11
+
12
+ import type { ReactNode } from "react";
13
+
14
+ import { Frame, Legend, areaFor, seriesColour } from "./Frame";
15
+ import type { Variant } from "./Frame";
16
+ import { extent, linePath, linearScale } from "./scale";
17
+ import { toneColor, type MeasureTone } from "@vitavision/ui";
18
+
19
+ /** One sampled profile of a {@link LineProfile}. */
20
+ export interface ProfileSeries {
21
+ /** Legend text, and the React key — unique within one chart. */
22
+ name: string;
23
+ /** `x` is arc length along the scan line or caliper axis, in pixels. */
24
+ points: { x: number; y: number }[];
25
+ /** Any CSS colour. Omitted: {@link seriesColour} of the series' index. */
26
+ colour?: string;
27
+ }
28
+
29
+ /** A detected edge or chosen crossing, drawn as a dashed vertical rule. */
30
+ export interface EdgeMark {
31
+ /** Position along the same arc-length axis as `ProfileSeries.points[].x`. */
32
+ position: number;
33
+ /** Text drawn above the rule, in the rule's colour. Omitted: no text. */
34
+ label?: string;
35
+ /** The rule's colour, as a `@vitavision/ui` measurement tone. Default `"signal"`. */
36
+ tone?: MeasureTone;
37
+ }
38
+
39
+ /** Props for {@link LineProfile}. */
40
+ export interface LineProfileProps {
41
+ /** The profiles, drawn in order. */
42
+ series: ProfileSeries[];
43
+ /** Detected edge positions, drawn as vertical rules over the series. */
44
+ edges?: EdgeMark[];
45
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
46
+ label: string;
47
+ /** x-axis title. Default `"arc length (px)"`. */
48
+ xLabel?: string;
49
+ /** y-axis title. Default `"value"`. */
50
+ yLabel?: string;
51
+ /** Fixed x domain. Omitted: the extent of every point's `x` and every edge's position. */
52
+ xDomain?: [number, number];
53
+ /** Fixed y domain. Omitted: the extent of every point's `y`. */
54
+ yDomain?: [number, number];
55
+ /** Rendered under the legend, inside the `<figcaption>`. */
56
+ footer?: ReactNode;
57
+ /** Show the legend row when there is more than one series. Default `true`. */
58
+ showLegend?: boolean;
59
+ /** Where the chart is going (see {@link Variant}). Default `"wide"`. */
60
+ variant?: Variant;
61
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
62
+ className?: string | undefined;
63
+ }
64
+
65
+ /**
66
+ * One or more series against arc length along a scan line or caliper axis, with detected
67
+ * edges as labelled vertical rules.
68
+ *
69
+ * @remarks
70
+ * An SVG `role="img"` named by `label`. The legend appears only for two or more series — a
71
+ * single profile is named by the chart's label.
72
+ */
73
+ export function LineProfile({
74
+ series,
75
+ edges = [],
76
+ label,
77
+ xLabel = "arc length (px)",
78
+ yLabel = "value",
79
+ xDomain,
80
+ yDomain,
81
+ footer,
82
+ showLegend = true,
83
+ variant = "wide",
84
+ className,
85
+ }: LineProfileProps) {
86
+ const allX = [...series.flatMap((entry) => entry.points.map((point) => point.x)), ...edges.map((edge) => edge.position)];
87
+ const allY = series.flatMap((entry) => entry.points.map((point) => point.y));
88
+ const plotArea = areaFor(variant);
89
+
90
+ const xScale = linearScale(xDomain ?? extent(allX), plotArea.x0, plotArea.x1);
91
+ const yScale = linearScale(yDomain ?? extent(allY), plotArea.y0, plotArea.y1);
92
+
93
+ const coloured = series.map((entry, index) => ({
94
+ ...entry,
95
+ colour: entry.colour ?? seriesColour(index),
96
+ }));
97
+
98
+ return (
99
+ <Frame
100
+ xScale={xScale}
101
+ yScale={yScale}
102
+ xLabel={xLabel}
103
+ yLabel={yLabel}
104
+ label={label}
105
+ variant={variant}
106
+ className={className}
107
+ footer={
108
+ <div className="flex flex-col gap-1">
109
+ {showLegend && series.length > 1 && (
110
+ <Legend
111
+ items={coloured.map((entry) => ({ label: entry.name, colour: entry.colour }))}
112
+ />
113
+ )}
114
+ {footer}
115
+ </div>
116
+ }
117
+ >
118
+ {coloured.map((entry) =>
119
+ entry.points.length === 1 ? (
120
+ <circle
121
+ key={entry.name}
122
+ cx={xScale.project(entry.points[0]?.x ?? 0)}
123
+ cy={yScale.project(entry.points[0]?.y ?? 0)}
124
+ r={2.5}
125
+ fill={entry.colour}
126
+ />
127
+ ) : (
128
+ <path
129
+ key={entry.name}
130
+ d={linePath(entry.points, xScale, yScale)}
131
+ fill="none"
132
+ stroke={entry.colour}
133
+ strokeWidth={1.5}
134
+ strokeLinejoin="round"
135
+ vectorEffect="non-scaling-stroke"
136
+ />
137
+ ),
138
+ )}
139
+
140
+ {edges.map((edge) => {
141
+ const x = xScale.project(edge.position);
142
+ const colour = toneColor(edge.tone, "signal");
143
+ return (
144
+ <g key={`${edge.position}-${edge.label ?? ""}-${edge.tone ?? ""}`}>
145
+ <line
146
+ x1={x}
147
+ x2={x}
148
+ y1={plotArea.y0}
149
+ y2={plotArea.y1}
150
+ stroke={colour}
151
+ strokeWidth={1.25}
152
+ strokeDasharray="3 2"
153
+ />
154
+ {edge.label && (
155
+ <text x={x} y={plotArea.y1 - 3} textAnchor="middle" fontSize={9} fill={colour}>
156
+ {edge.label}
157
+ </text>
158
+ )}
159
+ </g>
160
+ );
161
+ })}
162
+ </Frame>
163
+ );
164
+ }
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `@vitavision/charts` — small SVG charts over one shared scale and frame.
3
+ */
4
+
5
+ export {
6
+ Frame,
7
+ Legend,
8
+ areaFor,
9
+ plotArea,
10
+ seriesColour,
11
+ DEFECT_COLOUR,
12
+ NORMAL_COLOUR,
13
+ SERIES_COLOURS,
14
+ type FrameProps,
15
+ type LegendItem,
16
+ type LegendProps,
17
+ type Variant,
18
+ } from "./Frame";
19
+
20
+ export {
21
+ extent,
22
+ formatTick,
23
+ histogram,
24
+ linePath,
25
+ linearScale,
26
+ logScale,
27
+ niceStep,
28
+ padDomain,
29
+ type Scale,
30
+ type Tick,
31
+ } from "./scale";
32
+
33
+ export { LineChart, type LineChartProps, type Series } from "./LineChart";
34
+
35
+ export { StackedBars, type BarRow, type StackedBarsProps } from "./BarChart";
36
+
37
+ export { ScoreHistogram, type HistogramProps } from "./Histogram";
38
+
39
+ export {
40
+ LineProfile,
41
+ type EdgeMark,
42
+ type LineProfileProps,
43
+ type ProfileSeries,
44
+ } from "./LineProfile";