@vitavision/charts 0.7.1 → 0.8.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.
package/src/Histogram.tsx CHANGED
@@ -1,130 +1,159 @@
1
1
  /**
2
- * Score distribution by class, with a threshold drawn on it.
2
+ * A single-series histogram: one distribution, from raw values or from counts already binned.
3
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.
4
+ * Raw values are binned here; counts are for the caller that cannot hand over its samples —
5
+ * a 20 MP image's luminance is 256 numbers, not 20 million. Either way the bars are one
6
+ * `<path>`, and the bin under `cursor` is a second one in the selection colour.
11
7
  */
12
8
 
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");
9
+ import type { ReactNode } from "react";
18
10
 
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;
11
+ import { barsPath, binAt, binValues, cleanCounts, tallest } from "./bars";
12
+ import { FLUID_DEFAULT_HEIGHT, Frame, areaFor, seriesColour, useFluidSize, type Variant } from "./Frame";
13
+ import { Bands, Markers, PlotInteraction, type InteractionProps } from "./interaction";
14
+ import { linearScale, logScale } from "./scale";
15
+ import { ThresholdRule } from "./ThresholdRule";
22
16
 
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;
17
+ /** Props every {@link Histogram} takes, whichever way its data is given. */
18
+ export interface HistogramOptions extends InteractionProps {
33
19
  /** Accessible name of the chart (the SVG's `aria-label`). Required. */
34
20
  label: string;
21
+ /** x-axis title. */
22
+ xLabel?: string | undefined;
23
+ /** y-axis title. */
24
+ yLabel?: string | undefined;
25
+ /** Unit of x, appended to the x-axis title in parentheses: `luminance (DN)`. */
26
+ unit?: string | undefined;
27
+ /**
28
+ * A decision threshold on x, drawn as a dashed rule across the plot (as `ScoreHistogram`
29
+ * draws its own). Omitted or non-finite: none. For other x positions use `markers`.
30
+ */
31
+ threshold?: number | undefined;
32
+ /** Counts span decades in a long-tailed distribution; a log axis keeps the tail visible. */
33
+ logY?: boolean | undefined;
34
+ /** Where the chart is going (see {@link Variant}). Default `"panel"`. */
35
+ variant?: Variant | undefined;
36
+ /** For `variant="fluid"`: the chart's height in CSS pixels. Default 200. */
37
+ height?: number | undefined;
38
+ /** Rendered under the plot, inside the `<figcaption>`. */
39
+ footer?: ReactNode;
35
40
  /** Extra classes for the outer `<figure>`, merged with `cn`. */
36
41
  className?: string | undefined;
37
42
  }
38
43
 
44
+ /** A histogram given as raw samples, binned by the chart. */
45
+ export interface HistogramValues {
46
+ /** The samples. Non-finite values, and values outside `domain`, are ignored. */
47
+ values: ArrayLike<number>;
48
+ /** Number of equal-width bins. Default 32. */
49
+ bins?: number | undefined;
50
+ /** The x range the bins span. Omitted: the extent of `values`. */
51
+ domain?: [number, number] | undefined;
52
+ /** Not accepted with `values` — pass one or the other. */
53
+ counts?: undefined;
54
+ }
55
+
56
+ /** A histogram given as counts per bin, already binned by the caller. */
57
+ export interface HistogramCounts {
58
+ /** One count per bin, left to right; the bins are equal-width and fill `domain`. */
59
+ counts: ArrayLike<number>;
60
+ /** The x range the bins span. Required: without samples there is no extent to fall back on. */
61
+ domain: [number, number];
62
+ /** Not accepted with `counts` — pass one or the other. */
63
+ values?: undefined;
64
+ }
65
+
66
+ /**
67
+ * Props for {@link Histogram}: {@link HistogramOptions} plus data as either
68
+ * {@link HistogramValues} or {@link HistogramCounts}, never both.
69
+ */
70
+ export type HistogramProps = HistogramOptions & (HistogramValues | HistogramCounts);
71
+
39
72
  /**
40
- * Overlaid histograms of the normal and defect score distributions, with the threshold on
41
- * them.
73
+ * One distribution as a bar chart over equal-width bins.
42
74
  *
43
75
  * @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.
76
+ * An SVG `role="img"` named by `label`. `threshold` draws a dashed decision rule, `markers`
77
+ * tick the x axis, `bands` shade x ranges, `onHover` adds a crosshair and the x under it,
78
+ * `onPick` reports the x of a click, and `cursor` draws the bin containing an x chosen
79
+ * elsewhere in the selection colour (`--signal`) — no highlight when it lies outside the
80
+ * domain. Empty data draws an empty frame. For two classes sharing a threshold use
81
+ * {@link ScoreHistogram}.
46
82
  */
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);
83
+ export function Histogram(props: HistogramProps) {
84
+ const {
85
+ label,
86
+ xLabel,
87
+ yLabel,
88
+ unit,
89
+ logY = false,
90
+ variant = "panel",
91
+ height = FLUID_DEFAULT_HEIGHT,
92
+ footer,
93
+ className,
94
+ threshold,
95
+ bands,
96
+ markers,
97
+ cursor,
98
+ onHover,
99
+ onPick,
100
+ } = props;
101
+
102
+ const { counts, domain } =
103
+ props.counts !== undefined
104
+ ? cleanCounts(props.counts, props.domain)
105
+ : binValues(props.values, props.bins, props.domain);
106
+
107
+ const [fluidRef, fluidSize] = useFluidSize(height);
108
+ const size = variant === "fluid" ? fluidSize : undefined;
109
+ const plotArea = areaFor(variant, size);
59
110
 
60
111
  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;
112
+ const top = tallest(counts);
113
+ // Half a count of floor, so a bin of one is a visible bar on the log axis.
114
+ const yScale = logY ? logScale([0.5, top], plotArea.y0, plotArea.y1) : linearScale([0, top], plotArea.y0, plotArea.y1);
63
115
 
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
- );
116
+ const highlighted = binAt(counts.length, domain, cursor);
117
+ const hasHighlight = highlighted !== null && (counts[highlighted] ?? 0) > 0;
118
+ const xTitle = [xLabel, unit ? `(${unit})` : undefined].filter(Boolean).join(" ") || undefined;
80
119
 
81
120
  return (
82
121
  <Frame
83
122
  xScale={xScale}
84
123
  yScale={yScale}
85
- xLabel="anomaly score"
86
- yLabel="samples"
124
+ xLabel={xTitle}
125
+ yLabel={yLabel}
87
126
  label={label}
88
- variant="wide"
127
+ variant={variant}
89
128
  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
- }
129
+ size={size}
130
+ figureRef={variant === "fluid" ? fluidRef : undefined}
131
+ footer={footer}
113
132
  >
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"
133
+ {bands && bands.length > 0 && <Bands bands={bands} xScale={xScale} area={plotArea} />}
134
+ <path
135
+ data-bars=""
136
+ d={barsPath(counts, yScale, plotArea, { skip: hasHighlight ? highlighted : null })}
137
+ fill={seriesColour(0)}
138
+ opacity={0.8}
139
+ />
140
+ {hasHighlight && (
141
+ <path
142
+ data-cursor-bin={highlighted}
143
+ d={barsPath(counts, yScale, plotArea, { only: highlighted })}
144
+ fill="var(--signal)"
145
+ />
146
+ )}
147
+ <ThresholdRule value={threshold} xScale={xScale} area={plotArea} />
148
+ {markers && markers.length > 0 && <Markers markers={markers} xScale={xScale} area={plotArea} />}
149
+ {(onHover || onPick) && (
150
+ <PlotInteraction
151
+ xScale={xScale}
152
+ yScale={yScale}
153
+ area={plotArea}
154
+ series={[]}
155
+ onHover={onHover}
156
+ onPick={onPick}
128
157
  />
129
158
  )}
130
159
  </Frame>
@@ -0,0 +1,105 @@
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 { barsPath, tallest } from "./bars";
14
+ import { DEFECT_COLOUR, Frame, NORMAL_COLOUR, areaFor } from "./Frame";
15
+ import { extent, histogram, linearScale } from "./scale";
16
+ import { ThresholdRule } from "./ThresholdRule";
17
+
18
+ // The histogram is always given a whole panel, never a column of a grid.
19
+ const plotArea = areaFor("wide");
20
+
21
+ // Green for normal, red for defect — the verdict tokens, named once in `Frame`.
22
+ const NORMAL_FILL = NORMAL_COLOUR;
23
+ const DEFECT_FILL = DEFECT_COLOUR;
24
+
25
+ /** Props for {@link ScoreHistogram}. */
26
+ export interface ScoreHistogramProps {
27
+ /** Anomaly scores of the samples labelled normal. */
28
+ normal: number[];
29
+ /** Anomaly scores of the samples labelled defective. */
30
+ defect: number[];
31
+ /** The decision threshold, drawn as a dashed vertical rule. Omitted or non-finite: none. */
32
+ threshold?: number;
33
+ /** Number of equal-width bins over the union of both classes' scores. Default 32. */
34
+ bins?: number;
35
+ /** Accessible name of the chart (the SVG's `aria-label`). Required. */
36
+ label: string;
37
+ /** Extra classes for the outer `<figure>`, merged with `cn`. */
38
+ className?: string | undefined;
39
+ }
40
+
41
+ /**
42
+ * Overlaid histograms of the normal and defect score distributions, with the threshold on
43
+ * them.
44
+ *
45
+ * @remarks
46
+ * Always the `wide` variant. Painted in the verdict tokens (`--normal`, `--defect`); the
47
+ * legend names both classes with their counts, so the chart does not rely on colour alone.
48
+ */
49
+ export function ScoreHistogram({
50
+ normal,
51
+ defect,
52
+ threshold,
53
+ bins = 32,
54
+ label,
55
+ className,
56
+ }: ScoreHistogramProps) {
57
+ const domain = extent([...normal, ...defect]);
58
+ const normalBins = histogram(normal, domain, bins);
59
+ const defectBins = histogram(defect, domain, bins);
60
+ const top = tallest(normalBins, defectBins);
61
+
62
+ const xScale = linearScale(domain, plotArea.x0, plotArea.x1);
63
+ const yScale = linearScale([0, top], plotArea.y0, plotArea.y1);
64
+ return (
65
+ <Frame
66
+ xScale={xScale}
67
+ yScale={yScale}
68
+ xLabel="anomaly score"
69
+ yLabel="samples"
70
+ label={label}
71
+ variant="wide"
72
+ className={className}
73
+ footer={
74
+ <ul className="flex flex-wrap items-center gap-x-4 gap-y-1">
75
+ <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
+ />
81
+ <span className="font-mono text-xs">normal ({normal.length})</span>
82
+ </li>
83
+ <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
+ />
89
+ <span className="font-mono text-xs">defect ({defect.length})</span>
90
+ </li>
91
+ {threshold !== undefined && (
92
+ <li className="font-mono text-xs">threshold {threshold.toFixed(4)}</li>
93
+ )}
94
+ </ul>
95
+ }
96
+ >
97
+ {/* Normals first and defects over them: the defect bars are the smaller population
98
+ in every realistic split, so drawing them last keeps them from being buried. */}
99
+ <path data-bars="" d={barsPath(normalBins, yScale, plotArea)} fill={NORMAL_FILL} opacity={0.65} />
100
+ <path data-bars="" d={barsPath(defectBins, yScale, plotArea)} fill={DEFECT_FILL} opacity={0.65} />
101
+
102
+ <ThresholdRule value={threshold} xScale={xScale} area={plotArea} />
103
+ </Frame>
104
+ );
105
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The decision threshold of a histogram: a dashed rule across the plot at one x.
3
+ */
4
+
5
+ import type { PlotArea } from "./interaction";
6
+ import type { Scale } from "./scale";
7
+
8
+ /** A dashed vertical rule at `value`; nothing when it is missing or not finite. */
9
+ export function ThresholdRule({ value, xScale, area }: { value: number | undefined; xScale: Scale; area: PlotArea }) {
10
+ if (value === undefined || !Number.isFinite(value)) return null;
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
+ );
24
+ }
package/src/bars.ts ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The pure core of the histogram charts: binning, bin lookup and the one path that draws
3
+ * every bar. Nothing here touches React or the DOM.
4
+ */
5
+
6
+ import type { PlotArea } from "./interaction";
7
+ import type { Scale } from "./scale";
8
+ import { extent, padDomain } from "./scale";
9
+
10
+ /** Bins used when the caller does not say. */
11
+ export const DEFAULT_BINS = 32;
12
+
13
+ /** A histogram as the chart draws it: counts over equal-width bins spanning `domain`. */
14
+ export interface BinnedData {
15
+ /** One non-negative finite count per bin, left to right. */
16
+ counts: number[];
17
+ /** The x range the bins span, never degenerate (`low < high`). */
18
+ domain: [number, number];
19
+ }
20
+
21
+ /** A finite, ordered, non-degenerate domain; `[0, 1]` when `domain` is unusable. */
22
+ function usableDomain(low: number, high: number): [number, number] {
23
+ return padDomain(Math.min(low, high), Math.max(low, high));
24
+ }
25
+
26
+ /**
27
+ * Bin raw values into `bins` equal-width buckets.
28
+ *
29
+ * @param values - The samples. Non-finite values are ignored, and so are values outside an
30
+ * explicit `domain` (the upper edge itself belongs to the last bin).
31
+ * @param bins - Bucket count; a non-finite or sub-1 request falls back to 1, and `undefined`
32
+ * to {@link DEFAULT_BINS}.
33
+ * @param domain - The x range. Omitted: the data's extent. A single distinct value is
34
+ * widened so it lands in a middle bin rather than on an edge.
35
+ * @returns The counts and the domain they span.
36
+ */
37
+ export function binValues(
38
+ values: ArrayLike<number>,
39
+ bins: number | undefined,
40
+ domain?: [number, number],
41
+ ): BinnedData {
42
+ const count = bins === undefined ? DEFAULT_BINS : Number.isFinite(bins) ? Math.max(1, Math.floor(bins)) : 1;
43
+ const finite: number[] = [];
44
+ for (let index = 0; index < values.length; index += 1) {
45
+ const value = values[index];
46
+ if (value !== undefined && Number.isFinite(value)) finite.push(value);
47
+ }
48
+ const [low, high] = domain ? usableDomain(domain[0], domain[1]) : usableDomain(...extent(finite));
49
+ const counts = new Array<number>(count).fill(0);
50
+ const span = high - low;
51
+ for (const value of finite) {
52
+ if (value < low || value > high) continue;
53
+ const index = Math.min(count - 1, Math.floor(((value - low) / span) * count));
54
+ counts[index] = (counts[index] ?? 0) + 1;
55
+ }
56
+ return { counts, domain: [low, high] };
57
+ }
58
+
59
+ /**
60
+ * Take pre-binned counts as given, with the junk removed.
61
+ *
62
+ * @param counts - One count per bin, left to right.
63
+ * @param domain - The x range the bins span.
64
+ * @returns The counts with every non-finite or negative entry set to 0, and a usable domain.
65
+ */
66
+ export function cleanCounts(counts: ArrayLike<number>, domain: [number, number]): BinnedData {
67
+ const clean = Array.from(counts, (value) => (Number.isFinite(value) && value > 0 ? value : 0));
68
+ return { counts: clean, domain: usableDomain(domain[0], domain[1]) };
69
+ }
70
+
71
+ /**
72
+ * The bin containing `x`, or `null` when `x` is not finite, outside `domain`, or there are
73
+ * no bins. The domain's upper edge belongs to the last bin.
74
+ */
75
+ export function binAt(binCount: number, domain: [number, number], x: number | null | undefined): number | null {
76
+ if (x === null || x === undefined || !Number.isFinite(x) || binCount < 1) return null;
77
+ const [low, high] = domain;
78
+ if (x < low || x > high) return null;
79
+ return Math.min(binCount - 1, Math.floor(((x - low) / (high - low)) * binCount));
80
+ }
81
+
82
+ /**
83
+ * One SVG path `d` drawing every non-empty bar as a rectangle from the baseline.
84
+ *
85
+ * @param counts - The bins' counts.
86
+ * @param yScale - Maps a count to a pixel `y`.
87
+ * @param area - The plot area; the bins fill `x0`…`x1` and stand on `y0`.
88
+ * @param select - `{ skip: null }` (the default) draws every bar; `{ only: i }` draws just
89
+ * bin `i`; `{ skip: i }` draws all but bin `i` — so a highlighted bin is its own path.
90
+ */
91
+ export function barsPath(
92
+ counts: readonly number[],
93
+ yScale: Scale,
94
+ area: PlotArea,
95
+ select: { only: number } | { skip: number | null } = { skip: null },
96
+ ): string {
97
+ const width = (area.x1 - area.x0) / Math.max(1, counts.length);
98
+ // A hairline gap separates bars while they are wide enough to afford one.
99
+ const barWidth = Math.max(0.5, width > 3 ? width - 0.5 : width);
100
+ const parts: string[] = [];
101
+ counts.forEach((count, index) => {
102
+ if (count <= 0) return;
103
+ if ("only" in select ? index !== select.only : index === select.skip) return;
104
+ const x = area.x0 + index * width;
105
+ const y = yScale.project(count);
106
+ if (!Number.isFinite(y)) return;
107
+ parts.push(`M${x.toFixed(2)} ${area.y0}V${y.toFixed(2)}h${barWidth.toFixed(2)}V${area.y0}z`);
108
+ });
109
+ return parts.join("");
110
+ }
111
+
112
+ /** The largest count, at least 1, so an empty or all-zero histogram still has a y axis. */
113
+ export function tallest(...series: readonly (readonly number[])[]): number {
114
+ let max = 1;
115
+ for (const counts of series) for (const count of counts) if (count > max) max = count;
116
+ return max;
117
+ }
package/src/index.ts CHANGED
@@ -36,7 +36,15 @@ export { LineChart, type LineChartProps, type Series } from "./LineChart";
36
36
 
37
37
  export { StackedBars, type BarRow, type StackedBarsProps } from "./BarChart";
38
38
 
39
- export { ScoreHistogram, type HistogramProps } from "./Histogram";
39
+ export {
40
+ Histogram,
41
+ type HistogramCounts,
42
+ type HistogramOptions,
43
+ type HistogramProps,
44
+ type HistogramValues,
45
+ } from "./Histogram";
46
+
47
+ export { ScoreHistogram, type ScoreHistogramProps } from "./ScoreHistogram";
40
48
 
41
49
  export {
42
50
  LineProfile,