qvac-charts 0.3.0 → 0.4.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/README.md CHANGED
@@ -35,10 +35,37 @@ chart.summary // 'Ranked bar, 3 items, highlight USDT, $187B'
35
35
  chart.toSVG({ theme: 'light' }) // a 1080×1350 SVG string
36
36
  ```
37
37
 
38
- `summary` is one line a model can talk about the chart from, without seeing it. The model describes the data; the package picks the chart, does the arithmetic and draws it. There are 13 chart types, including a choropleth and a bubble map of the world or of one continent.
38
+ `summary` is one line a model can talk about the chart from, without seeing it. The model describes the data; the package picks the chart, does the arithmetic and draws it. There are 14 chart types, including a choropleth and a bubble map of the world or of one continent.
39
39
 
40
40
  A spec takes at most 30 items, the bound in `Chart.schema`; `Chart.from` throws a `RangeError` past it, or when no value is a finite number. Values that are not finite, such as `1e400` read from JSON, are dropped.
41
41
 
42
+ ### Scatter
43
+
44
+ A spec with `shape: 'pairs'` is a scatter: each item carries `x`, its number across, beside `value`, its number up. `horizontal` and `vertical` name the two axes. With `callout: 'trend'` the package fits a least-squares line, draws it and writes its R² on the chart and in `summary`; the highlighted item is the one point drawn with its name.
45
+
46
+ ```js
47
+ Chart.from({
48
+ shape: 'pairs',
49
+ title: 'More study, higher scores',
50
+ subtitle: 'Exam score against hours studied',
51
+ data: [
52
+ { label: 'Ana', x: 1, value: 52 },
53
+ { label: 'Bruno', x: 4, value: 70 },
54
+ { label: 'Carla', x: 8, value: 90 },
55
+ { label: 'Davi', x: 2, value: 94 }
56
+ ],
57
+ highlight: 'Davi',
58
+ scale: 'ones',
59
+ unit: 'number',
60
+ callout: 'trend',
61
+ horizontal: 'Hours studied',
62
+ vertical: 'Exam score',
63
+ source: 'User data'
64
+ }).summary // 'Scatter, 4 items, highlight Davi, 94, linear trend rising, R² 0.26'
65
+ ```
66
+
67
+ `scale` and `unit` apply to `value`; `x` is shown as written. Items without an `x` are left out, and `Chart.from` throws a `RangeError` when fewer than two have one.
68
+
42
69
  ### Brand mark
43
70
 
44
71
  The package ships no logo. A host that wants its mark in the footer passes it to `toSVG`; the source line then wraps short of it:
@@ -42,6 +42,9 @@ export declare class Chart {
42
42
  value: {
43
43
  type: string;
44
44
  };
45
+ x: {
46
+ type: string;
47
+ };
45
48
  group: {
46
49
  type: string;
47
50
  maxLength: number;
@@ -85,6 +88,14 @@ export declare class Chart {
85
88
  callout: {
86
89
  enum: string[];
87
90
  };
91
+ horizontal: {
92
+ type: string;
93
+ maxLength: number;
94
+ };
95
+ vertical: {
96
+ type: string;
97
+ maxLength: number;
98
+ };
88
99
  source: {
89
100
  type: string;
90
101
  maxLength: number;
package/dist-lib/index.js CHANGED
@@ -24,5 +24,11 @@ function summarize(chart) {
24
24
  const kind = name[0].toUpperCase() + name.slice(1);
25
25
  const lead = chart.data.find((d) => d.label === chart.highlight);
26
26
  const focus = lead ? `, highlight ${lead.label}, ${formatter(chart)(lead.value)}` : '';
27
- return `${kind}, ${chart.data.length} items${focus}`;
27
+ return `${kind}, ${chart.data.length} items${focus}${fitted(chart)}`;
28
+ }
29
+ function fitted({ trend }) {
30
+ if (!trend) {
31
+ return '';
32
+ }
33
+ return `, linear trend ${trend.slope < 0 ? 'falling' : 'rising'}, R² ${trend.r2.toFixed(2)}`;
28
34
  }
@@ -1,6 +1,7 @@
1
1
  import { bubbleMap, choropleth } from './maps.js';
2
2
  import { bubbles, donut, stacked, treemap, waffle } from './parts.js';
3
3
  import { radial, rankedBar } from './ranking.js';
4
+ import { scatter } from './scatter.js';
4
5
  import { slope } from './slope.js';
5
6
  import { column, line, multiLine } from './time.js';
6
7
  export const charts = {
@@ -16,5 +17,6 @@ export const charts = {
16
17
  'multi-line': multiLine,
17
18
  slope,
18
19
  choropleth,
19
- 'bubble-map': bubbleMap
20
+ 'bubble-map': bubbleMap,
21
+ scatter
20
22
  };
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { arc, bounds, dodge, largestRemainder, pack, polar, squarify } from '../geometry.js';
3
- import { text, wrap } from '../svg.js';
3
+ import { clamp, fit, stack, text, wrap } from '../svg.js';
4
4
  import { colors } from '../themes.js';
5
5
  const byValue = (data) => [...data].sort((a, c) => c.value - a.value);
6
6
  const sum = (data) => data.reduce((s, d) => s + d.value, 0);
@@ -216,12 +216,14 @@ export function stacked({ out, spec, t, b }) {
216
216
  const labelW = Math.min(240, Math.max(...rows.map((r) => r.length)) * 28 * 0.56) + 24;
217
217
  const x0 = b.x + labelW;
218
218
  const span = b.w - labelW;
219
+ const room = { width: labelW - 24, height: rowH * 0.9 };
220
+ const name = { ...fit(rows, room, [28, 24, 20]), ...room, x: b.x, weight: 700, fill: t.text };
219
221
  rows.forEach((r, ri) => {
220
222
  const cy = top + ri * rowH + rowH / 2;
221
223
  const cells = parts.map((p) => spec.data.find((d) => d.label === r && (d.group ?? '') === p)?.value ?? 0);
222
224
  const total = cells.reduce((s, v) => s + v, 0) || 1;
223
225
  let cx = x0;
224
- out.push(text(r, { x: b.x, y: cy + 10, size: 28, weight: 700, fill: t.text }));
226
+ out.push(...stack(clamp(r, name), { ...name, y: cy + 10 }));
225
227
  cells.forEach((v, pi) => {
226
228
  const w = (v / total) * span;
227
229
  if (w <= 0) {
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { ceiling, stroke } from '../geometry.js';
3
- import { text } from '../svg.js';
3
+ import { clamp, fit, stack, text } from '../svg.js';
4
4
  export function rankedBar(d) {
5
5
  const { out, spec, t, b, fmt } = d;
6
6
  const rows = [...spec.data].sort((a, c) => c.value - a.value);
@@ -8,6 +8,7 @@ export function rankedBar(d) {
8
8
  const max = ceiling(rows.map((r) => r.value));
9
9
  const rowH = Math.min(86, b.h / rows.length);
10
10
  const labelW = Math.min(300, Math.max(...rows.map((r) => r.label.length)) * 30 * 0.56);
11
+ const name = fit(rows.map((r) => r.label), { width: labelW, height: rowH * 0.9 }, [30, 26, 22, 18]);
11
12
  const x0 = b.x + 64 + labelW + 20;
12
13
  const span = b.x + b.w - x0 - 170;
13
14
  rows.forEach((r, i) => {
@@ -24,7 +25,13 @@ export function rankedBar(d) {
24
25
  fill: on ? t.bg : t.muted,
25
26
  anchor: 'middle'
26
27
  }));
27
- out.push(text(r.label, { x: b.x + 64, y: cy + 10, size: 30, weight: on ? 800 : 500, fill: t.text }));
28
+ out.push(...stack(clamp(r.label, { ...name, width: labelW }), {
29
+ ...name,
30
+ x: b.x + 64,
31
+ y: cy + 10,
32
+ weight: on ? 800 : 500,
33
+ fill: t.text
34
+ }));
28
35
  out.push(`<rect x="${x0}" y="${cy - rowH * 0.31}" width="${w}" height="${rowH * 0.62}" rx="6" fill="${fill}"/>`);
29
36
  out.push(text(fmt(r.value), {
30
37
  x: x0 + w + 14,
@@ -0,0 +1,2 @@
1
+ import type { Draw } from '../frame.ts';
2
+ export declare function scatter(d: Draw): void;
@@ -0,0 +1,70 @@
1
+ import { spread } from '../geometry.js';
2
+ import { halo, text } from '../svg.js';
3
+ import { paired } from '../trend.js';
4
+ const across = (v) => v.toLocaleString('en-US', { maximumFractionDigits: 2 });
5
+ export function scatter(d) {
6
+ const { spec, b } = d;
7
+ const pts = spec.data.filter(paired);
8
+ const xs = spread(pts.map((p) => p.x));
9
+ const ys = spread(pts.map((p) => p.value));
10
+ const [left, right, top, bottom] = [b.x + 100, b.x + b.w - 40, b.y + 70, b.y + b.h - 110];
11
+ const px = (v) => left + ((v - xs[0]) / (xs[xs.length - 1] - xs[0])) * (right - left);
12
+ const py = (v) => bottom - ((v - ys[0]) / (ys[ys.length - 1] - ys[0])) * (bottom - top);
13
+ const plot = { xs, ys, px, py, left, right, top, bottom };
14
+ axes(d, plot);
15
+ line(d, plot);
16
+ points(d, { plot, pts });
17
+ }
18
+ function axes({ out, spec, t, fmt }, { xs, ys, px, py, left, right, top, bottom }) {
19
+ const td = ys.some((v) => !Number.isInteger(v)) ? 1 : 0;
20
+ for (const v of ys) {
21
+ out.push(`<rect x="${left}" y="${py(v)}" width="${right - left}" height="1.5" fill="${t.faint}"/>`);
22
+ out.push(text(fmt(v, td), { x: left - 14, y: py(v) + 8, size: 22, fill: t.muted, anchor: 'end' }));
23
+ }
24
+ for (const v of xs) {
25
+ out.push(`<rect x="${px(v)}" y="${top}" width="1.5" height="${bottom - top}" fill="${t.faint}"/>`);
26
+ out.push(text(across(v), { x: px(v), y: bottom + 36, size: 22, fill: t.muted, anchor: 'middle' }));
27
+ }
28
+ const name = { size: 24, weight: 700, fill: t.text };
29
+ out.push(text(spec.vertical ?? '', { ...name, x: left - 100, y: top - 40 }));
30
+ out.push(text(spec.horizontal ?? '', { ...name, x: right, y: bottom + 84, anchor: 'end' }));
31
+ }
32
+ function line({ out, spec, t }, { xs, ys, px, py, right, top }) {
33
+ const fit = spec.trend;
34
+ if (!fit) {
35
+ return;
36
+ }
37
+ const at = (x) => fit.intercept + fit.slope * x;
38
+ const inside = (x) => Math.min(Math.max(x, xs[0]), xs[xs.length - 1]);
39
+ const [lo, hi] = [ys[0], ys[ys.length - 1]];
40
+ const ends = fit.slope
41
+ ? [(lo - fit.intercept) / fit.slope, (hi - fit.intercept) / fit.slope].sort((a, c) => a - c)
42
+ : [xs[0], xs[xs.length - 1]];
43
+ const [x0, x1] = ends.map(inside);
44
+ out.push(`<path d="M${px(x0)},${py(at(x0))}L${px(x1)},${py(at(x1))}" fill="none" stroke="${t.text}" stroke-width="4" stroke-dasharray="14 10" stroke-linecap="round" stroke-opacity="0.75"/>`);
45
+ out.push(text(`Linear trend, R² = ${fit.r2.toFixed(2)}`, {
46
+ x: right,
47
+ y: top - 40,
48
+ size: 24,
49
+ weight: 700,
50
+ fill: t.text,
51
+ anchor: 'end'
52
+ }));
53
+ }
54
+ function points({ out, spec, t, fmt }, { plot: { px, py, left, right }, pts }) {
55
+ const on = pts.find((p) => p.label === spec.highlight);
56
+ for (const p of pts) {
57
+ if (p !== on) {
58
+ out.push(`<circle cx="${px(p.x)}" cy="${py(p.value)}" r="11" fill="${t.palette[3]}" fill-opacity="0.9" stroke="${t.bg}" stroke-width="3"/>`);
59
+ }
60
+ }
61
+ if (!on) {
62
+ return;
63
+ }
64
+ const [x, y] = [px(on.x), py(on.value)];
65
+ const end = x > (left + right) / 2;
66
+ const name = { x: end ? x - 24 : x + 24, anchor: end ? 'end' : 'start', stroke: t.bg };
67
+ out.push(`<circle cx="${x}" cy="${y}" r="15" fill="${t.accent}" stroke="${t.bg}" stroke-width="3"/>`);
68
+ out.push(halo(on.label, { ...name, y: y + 2, size: 26, weight: 800, fill: t.accent }));
69
+ out.push(halo(`${across(on.x)}, ${fmt(on.value)}`, { ...name, y: y + 30, size: 22, fill: t.muted }));
70
+ }
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { ceiling, dodge, ticks } from '../geometry.js';
3
- import { text, wrap } from '../svg.js';
3
+ import { clamp, fit, text, wrap } from '../svg.js';
4
4
  function grid({ out, t, fmt }, { py, left, width, max }) {
5
5
  const tk = ticks(max);
6
6
  const td = tk.some((v) => !Number.isInteger(v)) ? 1 : 0;
@@ -9,6 +9,16 @@ function grid({ out, t, fmt }, { py, left, width, max }) {
9
9
  out.push(text(fmt(v, td), { x: left - 14, y: py(v) + 8, size: 22, fill: t.muted, anchor: 'end' }));
10
10
  }
11
11
  }
12
+ function names({ t }, { names, x, step, y }) {
13
+ const every = Math.ceil(64 / step);
14
+ const width = step * every - 8;
15
+ const kept = (i) => (names.length - 1 - i) % every === 0;
16
+ const shown = names.filter((_, i) => kept(i));
17
+ const { size, lines, gap } = fit(shown, { width, height: 72 }, [24, 20, 16]);
18
+ return (i) => kept(i)
19
+ ? clamp(names[i], { width, size, lines }).map((l, j) => text(l, { x: x(i), y: y + j * gap, size, fill: t.muted, anchor: 'middle' }))
20
+ : [];
21
+ }
12
22
  export function line(d) {
13
23
  const { out, spec, t, b } = d;
14
24
  const pts = spec.data;
@@ -18,13 +28,13 @@ export function line(d) {
18
28
  const py = (v) => b.y + b.h - pad.b - (v / max) * (b.h - pad.t - pad.b);
19
29
  const axes = { px, py, left: b.x + pad.l, width: b.w - pad.l - pad.r };
20
30
  grid(d, { ...axes, max });
21
- pts.forEach((p, i) => out.push(text(p.label, {
22
- x: px(i),
23
- y: b.y + b.h - pad.b + 40,
24
- size: 24,
25
- fill: t.muted,
26
- anchor: 'middle'
27
- })));
31
+ const name = names(d, {
32
+ names: pts.map((p) => p.label),
33
+ x: px,
34
+ step: axes.width / Math.max(1, pts.length - 1),
35
+ y: b.y + b.h - pad.b + 40
36
+ });
37
+ pts.forEach((_, i) => out.push(...name(i)));
28
38
  const path = pts.map((p, i) => `${i ? 'L' : 'M'}${px(i)},${py(p.value)}`).join('');
29
39
  out.push(`<defs><linearGradient id="area" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${t.accent}" stop-opacity="0.45"/><stop offset="1" stop-color="${t.accent}" stop-opacity="0"/></linearGradient></defs>`);
30
40
  out.push(`<path d="${path}L${px(pts.length - 1)},${py(0)}L${px(0)},${py(0)}Z" fill="url(#area)"/>`);
@@ -62,10 +72,17 @@ export function column(d) {
62
72
  const base = b.y + b.h - 60;
63
73
  const slot = b.w / pts.length;
64
74
  const bw = Math.min(140, slot * 0.64);
75
+ const left = (i) => b.x + i * slot + (slot - bw) / 2;
76
+ const name = names(d, {
77
+ names: pts.map((p) => p.label),
78
+ x: (i) => left(i) + bw / 2,
79
+ step: slot,
80
+ y: base + 40
81
+ });
65
82
  pts.forEach((p, i) => {
66
83
  const on = p.label === hl;
67
84
  const h = (Math.max(0, p.value) / max) * (base - top);
68
- const x = b.x + i * slot + (slot - bw) / 2;
85
+ const x = left(i);
69
86
  out.push(`<rect x="${x}" y="${base - h}" width="${bw}" height="${h}" rx="6" fill="${on ? t.accent : t.base}"/>`);
70
87
  out.push(text(fmt(p.value), {
71
88
  x: x + bw / 2,
@@ -75,7 +92,7 @@ export function column(d) {
75
92
  fill: on ? t.accent : t.text,
76
93
  anchor: 'middle'
77
94
  }));
78
- out.push(text(p.label, { x: x + bw / 2, y: base + 40, size: 24, fill: t.muted, anchor: 'middle' }));
95
+ out.push(...name(i));
79
96
  });
80
97
  out.push(`<rect x="${b.x}" y="${base}" width="${b.w}" height="2" fill="${t.faint}"/>`);
81
98
  callout(d, { x: b.x, y: b.y + 100, w: 420 });
@@ -91,7 +108,13 @@ export function multiLine(d) {
91
108
  const color = (g, i) => g === spec.highlight ? t.accent : t.palette[(i + 1) % t.palette.length];
92
109
  const ends = [];
93
110
  grid(d, { px, py, left: b.x + pad.l, width: b.w - pad.l - pad.r, max });
94
- labels.forEach((l, i) => out.push(text(l, { x: px(i), y: b.y + b.h - pad.b + 40, size: 24, fill: t.muted, anchor: 'middle' })));
111
+ const name = names(d, {
112
+ names: labels,
113
+ x: px,
114
+ step: (b.w - pad.l - pad.r) / Math.max(1, labels.length - 1),
115
+ y: b.y + b.h - pad.b + 40
116
+ });
117
+ labels.forEach((_, i) => out.push(...name(i)));
95
118
  groups.forEach((g, gi) => {
96
119
  const pts = labels.flatMap((l, i) => {
97
120
  const p = spec.data.find((q) => (q.group ?? '') === g && q.label === l);
@@ -48,3 +48,4 @@ export declare function bounds(cs: ReadonlyArray<Circle>): Bounds;
48
48
  export declare function squarify(values: ReadonlyArray<number>, rect: Rect): Rect[];
49
49
  export declare function ceiling(values: ReadonlyArray<number>): number;
50
50
  export declare function ticks(max: number): number[];
51
+ export declare function spread(values: ReadonlyArray<number>): number[];
@@ -164,3 +164,13 @@ export function ticks(max) {
164
164
  }
165
165
  return out;
166
166
  }
167
+ export function spread(values) {
168
+ const lo = Math.min(...values);
169
+ const hi = Math.max(...values);
170
+ const range = hi - lo || Math.abs(hi) || 1;
171
+ const step = Math.pow(10, Math.floor(Math.log10(range / 4)));
172
+ const unit = [1, 2, 2.5, 5].map((m) => m * step).find((s) => range / s <= 5) ?? 10 * step;
173
+ const first = Math.floor(lo / unit);
174
+ const count = Math.max(1, Math.ceil(hi / unit - 1e-9) - first);
175
+ return Array.from({ length: count + 1 }, (_, i) => (first + i) * unit);
176
+ }
@@ -1,6 +1,7 @@
1
1
  import { lookup, mapFor, WORLD } from './places.js';
2
2
  import { pick } from './pick.js';
3
3
  import { MAX_ITEMS } from './schema.js';
4
+ import { paired, trend } from './trend.js';
4
5
  const prefixes = {
5
6
  dollars: '$',
6
7
  euros: '€',
@@ -80,7 +81,10 @@ export function normalize(input, maps) {
80
81
  maps,
81
82
  from: spec.from,
82
83
  to: spec.to,
83
- annotations: spec.annotations ?? []
84
+ annotations: spec.annotations ?? [],
85
+ horizontal: spec.horizontal,
86
+ vertical: spec.vertical,
87
+ trend: type === 'scatter' && spec.callout === 'trend' ? trend(data.filter(paired)) : undefined
84
88
  };
85
89
  }
86
90
  function largest(max) {
@@ -93,7 +97,11 @@ function largest(max) {
93
97
  function finite(spec) {
94
98
  const data = spec.data
95
99
  .filter((d) => Number.isFinite(d.value))
96
- .map((d) => ({ ...d, previous: Number.isFinite(d.previous) ? d.previous : undefined }));
100
+ .map((d) => ({
101
+ ...d,
102
+ previous: Number.isFinite(d.previous) ? d.previous : undefined,
103
+ x: Number.isFinite(d.x) ? d.x : undefined
104
+ }));
97
105
  if (data.length === 0) {
98
106
  throw new RangeError('A chart needs at least one finite value');
99
107
  }
@@ -115,7 +123,14 @@ function arranged(input, maps) {
115
123
  if (spec.shape === 'change' && !spec.data.some((d) => d.previous !== undefined)) {
116
124
  spec = pairs(spec);
117
125
  }
118
- return spec;
126
+ return spec.shape === 'pairs' || spec.type === 'scatter' ? scattered(spec) : spec;
127
+ }
128
+ function scattered(spec) {
129
+ const data = spec.data.filter(paired);
130
+ if (data.length < 2) {
131
+ throw new RangeError('Pairs need two numbers per item: x across and value up');
132
+ }
133
+ return { ...spec, shape: 'pairs', type: undefined, data };
119
134
  }
120
135
  function unitSuffix(unit, scale) {
121
136
  return unit === 'percent' ? '%' : (scale ?? '');
@@ -9,6 +9,9 @@ export function pick(spec, data) {
9
9
  if (spec.shape === 'ranking') {
10
10
  return v === 'radial' && n <= 10 ? 'radial' : 'ranked-bar';
11
11
  }
12
+ if (spec.shape === 'pairs') {
13
+ return 'scatter';
14
+ }
12
15
  if (spec.shape === 'sizes') {
13
16
  return 'bubbles';
14
17
  }
@@ -32,6 +32,9 @@ export declare const chartSchema: {
32
32
  value: {
33
33
  type: string;
34
34
  };
35
+ x: {
36
+ type: string;
37
+ };
35
38
  group: {
36
39
  type: string;
37
40
  maxLength: number;
@@ -75,6 +78,14 @@ export declare const chartSchema: {
75
78
  callout: {
76
79
  enum: string[];
77
80
  };
81
+ horizontal: {
82
+ type: string;
83
+ maxLength: number;
84
+ };
85
+ vertical: {
86
+ type: string;
87
+ maxLength: number;
88
+ };
78
89
  source: {
79
90
  type: string;
80
91
  maxLength: number;
@@ -4,12 +4,13 @@ const item = {
4
4
  properties: {
5
5
  label: { type: 'string', maxLength: 32 },
6
6
  value: { type: 'number' },
7
+ x: { type: 'number' },
7
8
  group: { type: 'string', maxLength: 24 }
8
9
  },
9
10
  required: ['label', 'value'],
10
11
  additionalProperties: false
11
12
  };
12
- export const SHAPES = ['ranking', 'parts', 'over-time', 'change', 'sizes', 'places'];
13
+ export const SHAPES = ['ranking', 'parts', 'over-time', 'change', 'sizes', 'places', 'pairs'];
13
14
  export const VARIANTS = [
14
15
  'bar',
15
16
  'radial',
@@ -47,7 +48,9 @@ export const chartSchema = {
47
48
  additionalProperties: false
48
49
  }
49
50
  },
50
- callout: { enum: ['none', 'share', 'growth', 'ratio'] },
51
+ callout: { enum: ['none', 'share', 'growth', 'ratio', 'trend'] },
52
+ horizontal: { type: 'string', maxLength: 32 },
53
+ vertical: { type: 'string', maxLength: 32 },
51
54
  source: { type: 'string', maxLength: 120 }
52
55
  },
53
56
  required: [
@@ -1,8 +1,10 @@
1
1
  import type { Maps } from './places.ts';
2
- export type ChartType = 'ranked-bar' | 'bubbles' | 'treemap' | 'line' | 'column' | 'multi-line' | 'donut' | 'waffle' | 'stacked' | 'slope' | 'radial' | 'choropleth' | 'bubble-map';
2
+ import type { Trend } from './trend.ts';
3
+ export type ChartType = 'ranked-bar' | 'bubbles' | 'treemap' | 'line' | 'column' | 'multi-line' | 'donut' | 'waffle' | 'stacked' | 'slope' | 'radial' | 'choropleth' | 'bubble-map' | 'scatter';
3
4
  export interface Item {
4
5
  label: string;
5
6
  value: number;
7
+ x?: number | undefined;
6
8
  group?: string | undefined;
7
9
  previous?: number | undefined;
8
10
  note?: string | undefined;
@@ -31,6 +33,8 @@ export interface Spec {
31
33
  annotations?: ReadonlyArray<Annotation>;
32
34
  callout?: string | Callout;
33
35
  source: string;
36
+ horizontal?: string;
37
+ vertical?: string;
34
38
  map?: string;
35
39
  from?: string | undefined;
36
40
  to?: string | undefined;
@@ -55,4 +59,7 @@ export interface Chart {
55
59
  from: string | undefined;
56
60
  to: string | undefined;
57
61
  annotations: ReadonlyArray<Annotation>;
62
+ horizontal: string | undefined;
63
+ vertical: string | undefined;
64
+ trend: Trend | undefined;
58
65
  }
@@ -17,5 +17,23 @@ export interface Measure {
17
17
  width: number;
18
18
  size: number;
19
19
  }
20
- export declare function wrap(str: string, { width, size }: Measure): string[];
20
+ export declare function wrap(str: string, m: Measure): string[];
21
+ export interface Clamp extends Measure {
22
+ lines: number;
23
+ }
24
+ export declare function clamp(str: string, { lines, ...m }: Clamp): string[];
25
+ export interface Room {
26
+ width: number;
27
+ height: number;
28
+ }
29
+ export interface Fit {
30
+ size: number;
31
+ lines: number;
32
+ gap: number;
33
+ }
34
+ export declare function fit(strs: ReadonlyArray<string>, room: Room, sizes: ReadonlyArray<number>): Fit;
35
+ export interface Stack extends TextStyle {
36
+ gap: number;
37
+ }
38
+ export declare function stack(lines: ReadonlyArray<string>, { gap, ...style }: Stack): string[];
21
39
  export declare function fixed(svg: string): string;
@@ -13,8 +13,8 @@ export function text(str, style) {
13
13
  export function halo(str, { stroke, ...style }) {
14
14
  return text(str, style).replace('<text ', `<text stroke="${stroke}" stroke-width="6" stroke-linejoin="round" paint-order="stroke" `);
15
15
  }
16
- export function wrap(str, { width, size }) {
17
- const per = Math.floor(width / (size * 0.54));
16
+ export function wrap(str, m) {
17
+ const per = chars(m);
18
18
  const lines = [];
19
19
  let line = '';
20
20
  for (const word of str.split(/\s+/)) {
@@ -31,6 +31,38 @@ export function wrap(str, { width, size }) {
31
31
  }
32
32
  return lines;
33
33
  }
34
+ export function clamp(str, { lines, ...m }) {
35
+ const per = chars(m);
36
+ const all = wrap(str, m);
37
+ const kept = all.slice(0, lines);
38
+ if (all.length > lines) {
39
+ kept[lines - 1] += '…';
40
+ }
41
+ return kept.map((l) => (l.length > per ? l.slice(0, Math.max(0, per - 1)).trimEnd() + '…' : l));
42
+ }
43
+ export function fit(strs, room, sizes) {
44
+ for (const size of sizes) {
45
+ const f = leading(size, room);
46
+ if (strs.every((s) => whole(s, { ...f, width: room.width }))) {
47
+ return f;
48
+ }
49
+ }
50
+ return leading(Math.min(...sizes), room);
51
+ }
52
+ function leading(size, { height }) {
53
+ const gap = size * 1.15;
54
+ return { size, gap, lines: Math.max(1, Math.floor(height / gap)) };
55
+ }
56
+ function whole(str, { lines, ...m }) {
57
+ const all = wrap(str, m);
58
+ return all.length <= lines && all.every((l) => l.length <= chars(m));
59
+ }
60
+ export function stack(lines, { gap, ...style }) {
61
+ return lines.map((l, j) => text(l, { ...style, y: style.y + (j - (lines.length - 1) / 2) * gap }));
62
+ }
63
+ function chars({ width, size }) {
64
+ return Math.floor(width / (size * 0.54));
65
+ }
34
66
  export function fixed(svg) {
35
67
  return svg.replace(/<[^<>]+>/g, (tag) => tag.replace(/(?<![\w-])([\w-]+)="([^"]*)"/g, rounded));
36
68
  }
@@ -0,0 +1,14 @@
1
+ export interface Trend {
2
+ slope: number;
3
+ intercept: number;
4
+ r2: number;
5
+ }
6
+ export interface Pair {
7
+ x: number;
8
+ value: number;
9
+ }
10
+ export declare function trend(pairs: ReadonlyArray<Pair>): Trend | undefined;
11
+ export interface Across {
12
+ x?: number | undefined;
13
+ }
14
+ export declare function paired<T extends Across>(d: T): d is T & Pair;
@@ -0,0 +1,16 @@
1
+ export function trend(pairs) {
2
+ const n = pairs.length;
3
+ const mx = pairs.reduce((s, p) => s + p.x, 0) / n;
4
+ const my = pairs.reduce((s, p) => s + p.value, 0) / n;
5
+ const sxx = pairs.reduce((s, p) => s + (p.x - mx) ** 2, 0);
6
+ const syy = pairs.reduce((s, p) => s + (p.value - my) ** 2, 0);
7
+ const sxy = pairs.reduce((s, p) => s + (p.x - mx) * (p.value - my), 0);
8
+ if (n < 3 || sxx === 0 || syy === 0) {
9
+ return undefined;
10
+ }
11
+ const slope = sxy / sxx;
12
+ return { slope, intercept: my - slope * mx, r2: (sxy * sxy) / (sxx * syy) };
13
+ }
14
+ export function paired(d) {
15
+ return d.x !== undefined;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qvac-charts",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Renders a small JSON chart spec into an SVG, on Bare and Node",
5
5
  "type": "module",
6
6
  "exports": {