@n1kname/charts 0.2.0 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1kname/charts",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,7 +8,8 @@
8
8
  "./donut": "./src/donut.mjs",
9
9
  "./plot": "./src/plot.mjs",
10
10
  "./theme": "./src/theme.mjs",
11
- "./lines": "./src/lines.mjs"
11
+ "./lines": "./src/lines.mjs",
12
+ "./bars": "./src/bars.mjs"
12
13
  },
13
14
  "dependencies": {
14
15
  "@observablehq/plot": "0.6.17",
@@ -27,6 +28,6 @@
27
28
  "src"
28
29
  ],
29
30
  "scripts": {
30
- "check": "node src/donut.test.mjs && node src/lines.test.mjs"
31
+ "check": "node src/donut.test.mjs && node src/lines.test.mjs && node src/bars.test.mjs"
31
32
  }
32
33
  }
package/src/bars.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // Bars on one axis, one per row: a single value, or a few series stacked in the order given,
2
+ // bottom to top. Returns Plot options without a style, so the same chart draws at build time
3
+ // (renderPlot) or in the browser (Plot.plot with the page's style).
4
+ //
5
+ // Rows are wide: one object per x, a number (or null for none) per series key. Positive
6
+ // values stack up from zero and negative ones down, so a month that returned more than it
7
+ // bought still reads. A row can be drawn fainter (`fade`) and with a dashed edge (`dashed`),
8
+ // for figures that are not settled yet; say what each means in a Legend.
9
+
10
+ import * as Plot from '@observablehq/plot';
11
+ import { chrome, tipStyle } from './theme.mjs';
12
+
13
+ const plain = (v, digits) => v.toFixed(digits);
14
+
15
+ export const bars = (
16
+ {
17
+ rows,
18
+ x,
19
+ series,
20
+ unit,
21
+ digits = 0,
22
+ format = plain,
23
+ height = 240,
24
+ // Which x labels to print; the rest stay positions on the scale. Gets (label, index, width).
25
+ tick = (label) => label,
26
+ // Each end 'auto' or a number. 'auto' always takes in zero, so bars stand on it.
27
+ y = ['auto', 'auto'],
28
+ // The total written on top of each bar.
29
+ values = false,
30
+ // Opacity per row, 1 for a settled figure.
31
+ fade = () => 1,
32
+ // A dashed edge per row, in the series' colour.
33
+ dashed = () => false,
34
+ // The tooltip's text per row. By default the label, each series from the top, and the unit.
35
+ title,
36
+ // The gap between bars, as a share of each bar's room.
37
+ padding = 0.28,
38
+ },
39
+ width,
40
+ ) => {
41
+ const has = (r, key) => typeof r[key] === 'number';
42
+ // Where each series' piece of each bar starts and ends.
43
+ const pieces = series.map(() => []);
44
+ for (const r of rows) {
45
+ let up = 0;
46
+ let down = 0;
47
+ series.forEach((s, i) => {
48
+ if (!has(r, s.key)) return;
49
+ const v = r[s.key];
50
+ const from = v >= 0 ? up : down;
51
+ if (v >= 0) up += v;
52
+ else down += v;
53
+ pieces[i].push({ row: r, y1: from, y2: from + v });
54
+ });
55
+ }
56
+ const top = (r) => series.reduce((sum, s) => sum + (has(r, s.key) && r[s.key] > 0 ? r[s.key] : 0), 0);
57
+ const bottom = (r) => series.reduce((sum, s) => sum + (has(r, s.key) && r[s.key] < 0 ? r[s.key] : 0), 0);
58
+ const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
59
+ const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
60
+ const domain = [
61
+ y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
62
+ y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
63
+ ];
64
+ const says =
65
+ title ??
66
+ ((r) => [r[x], ...[...series].reverse().filter((s) => has(r, s.key)).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
67
+
68
+ // Settled rows and dashed ones are separate marks, because a dash cannot vary per bar.
69
+ const piece = (s, i, rowsOf, edge) =>
70
+ Plot.barY(rowsOf, {
71
+ x: (p) => p.row[x],
72
+ y1: 'y1',
73
+ y2: 'y2',
74
+ fill: s.color,
75
+ fillOpacity: (p) => fade(p.row),
76
+ stroke: edge ? s.color : 'var(--c-surface)',
77
+ strokeWidth: 1,
78
+ strokeDasharray: edge ? '3 2' : undefined,
79
+ // The last series is the top of the bar: rounded there, square on the baseline.
80
+ ...(i === series.length - 1 ? { ry1: 4 } : {}),
81
+ });
82
+
83
+ return {
84
+ width,
85
+ height,
86
+ marginTop: values ? 24 : 10,
87
+ marginLeft: 44,
88
+ marginRight: 4,
89
+ marginBottom: 30,
90
+ x: { type: 'band', domain: rows.map((r) => r[x]), padding, label: null, tickSize: 0, tickFormat: (v, i) => tick(v, i, width) },
91
+ y: { domain, nice: true, label: null, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, 0) },
92
+ opacity: { type: 'identity' },
93
+ marks: [
94
+ Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
95
+ // The bar under the pointer, behind the bars.
96
+ Plot.barY(drawn, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
97
+ ...series.flatMap((s, i) => [
98
+ piece(s, i, pieces[i].filter((p) => !dashed(p.row)), false),
99
+ piece(s, i, pieces[i].filter((p) => dashed(p.row)), true),
100
+ ]),
101
+ ...(values
102
+ ? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12 })]
103
+ : []),
104
+ Plot.ruleY([0], { stroke: chrome.axis }),
105
+ Plot.tip(drawn, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
106
+ ],
107
+ };
108
+ };
@@ -0,0 +1,67 @@
1
+ // Synthetic data only, like everything in this repo.
2
+ import assert from 'node:assert/strict';
3
+ import { bars } from './bars.mjs';
4
+ import { renderPlot } from './plot.mjs';
5
+
6
+ const rows = [
7
+ { month: 'M1', a: 10, b: 4, c: 2 },
8
+ { month: 'M2', a: 10, b: 6, c: -3 },
9
+ { month: 'M3', a: 10, b: null, c: 1 },
10
+ { month: 'M4', a: 10, b: 8, c: 5, kind: 'estimate' },
11
+ { month: 'M5', a: 10, b: 9, c: 6, kind: 'projection' },
12
+ ];
13
+ const series = [
14
+ { key: 'a', label: 'Ash', color: 'var(--c-chart-2)' },
15
+ { key: 'b', label: 'Beech', color: 'var(--c-chart-1)' },
16
+ { key: 'c', label: 'Cedar', color: 'var(--c-chart-3)' },
17
+ ];
18
+ const FADE = { estimate: 0.5, projection: 0.22 };
19
+ const spec = {
20
+ rows,
21
+ x: 'month',
22
+ series,
23
+ unit: 'units',
24
+ digits: 1,
25
+ tick: (v, i) => (i % 2 ? '' : v),
26
+ fade: (r) => FADE[r.kind] ?? 1,
27
+ dashed: (r) => r.kind === 'projection',
28
+ };
29
+
30
+ const options = bars(spec, 600);
31
+ const svg = renderPlot(options);
32
+ const ticks = [...svg.matchAll(/<text[^>]*>(M\d)<\/text>/g)].map((m) => m[1]);
33
+ assert.deepEqual(ticks, ['M1', 'M3', 'M5'], 'only the ticks the tick function prints');
34
+ assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
35
+
36
+ // The pieces of a bar: each series from where the one below it stopped.
37
+ const [, ashSolid, , beechSolid, , cedarSolid, cedarDashed] = options.marks.slice(1);
38
+ const span = (mark, i) => [mark.data[i].y1, mark.data[i].y2];
39
+ assert.deepEqual(span(beechSolid, 0), [10, 14], 'a series stacks on the one before it');
40
+ assert.deepEqual(span(cedarSolid, 0), [14, 16], 'and the last on top');
41
+ assert.deepEqual(span(cedarSolid, 1), [0, -3], 'a negative value hangs below zero instead');
42
+ assert.deepEqual(span(cedarSolid, 2), [10, 11], 'a missing value is left out, not drawn as 0');
43
+ assert.ok(!beechSolid.data.some((p) => p.row.month === 'M3'), 'and has no piece of its own');
44
+ assert.equal(ashSolid.data.length, 4, 'settled and estimated rows are drawn solid');
45
+ assert.equal(cedarDashed.data.length, 1, 'a dashed row is drawn apart, with its dashes');
46
+ assert.ok(svg.includes('stroke-dasharray="3 2"'), 'a dashed row is dashed');
47
+
48
+ // Fades: an estimate fainter, a projection fainter again.
49
+ const opacity = [...svg.matchAll(/fill="var\(--c-chart-2\)"[^>]*>((?:<(?:path|rect)[^>]*>)+)/g)]
50
+ .flatMap((m) => [...m[1].matchAll(/fill-opacity="([\d.]+)"/g)].map((o) => Number(o[1])));
51
+ assert.deepEqual(opacity, [1, 1, 1, 0.5, 0.22], 'settled rows are solid, an estimate fainter, a projection fainter again');
52
+
53
+ // The domain holds the highest stack and the lowest negative.
54
+ assert.deepEqual(options.y.domain, [-3, 25], 'the y domain runs from the lowest piece to the highest stack');
55
+
56
+ // The tooltip: each series from the top, a missing one left out.
57
+ const tip = options.marks.at(-1);
58
+ const title = (i) => tip.channels.title.value(rows[i]);
59
+ assert.equal(title(0), 'M1\nCedar 2.0\nBeech 4.0\nAsh 10.0\nunits');
60
+ assert.equal(title(2), 'M3\nCedar 1.0\nAsh 10.0\nunits', 'a missing value is left out, not shown as 0');
61
+
62
+ // One series with its value on top of each bar.
63
+ const single = bars({ rows: rows.map((r) => ({ year: r.month, v: r.a + r.month.length })), x: 'year', series: [{ key: 'v', label: 'Value', color: 'var(--c-chart-1)' }], unit: 'units', values: true }, 400);
64
+ const labels = [...renderPlot(single).matchAll(/<text[^>]*>(\d+)<\/text>/g)].map((m) => m[1]);
65
+ assert.deepEqual(labels.slice(-5), ['12', '12', '12', '12', '12'], 'with values, each bar carries its total');
66
+
67
+ console.log('bars: all assertions pass');
package/src/index.mjs CHANGED
@@ -2,3 +2,4 @@ export * from './theme.mjs';
2
2
  export * from './donut.mjs';
3
3
  export * from './plot.mjs';
4
4
  export * from './lines.mjs';
5
+ export * from './bars.mjs';
package/src/lines.mjs CHANGED
@@ -35,9 +35,12 @@ export const lines = (
35
35
  const domain = [y[0] === 'auto' ? Math.min(...values) : y[0], y[1] === 'auto' ? Math.max(...values) : y[1]];
36
36
 
37
37
  // The tooltip names every series with a value at that x. A silent one, such as the
38
- // dashed rest of another line, only where the line it `continues` has none.
39
- const told = (r) =>
40
- series.filter((s) => has(r, s.key) && (!s.silent || (s.continues && !has(r, s.continues))));
38
+ // dashed rest of another line, only where the line it `continues` has none, and after
39
+ // the settled ones.
40
+ const told = (r) => [
41
+ ...series.filter((s) => !s.silent && has(r, s.key)),
42
+ ...series.filter((s) => s.silent && s.continues && has(r, s.key) && !has(r, s.continues)),
43
+ ];
41
44
  const tipped = rows.filter((r) => told(r).length);
42
45
  const title = (r) => [r[x], ...told(r).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n');
43
46
 
@@ -38,6 +38,10 @@ assert.equal(title(1), 'W2\nAlder 3.0\nunits', 'a missing value is left out, no
38
38
  assert.equal(title(3), 'W4\nAlder 6.0\nBirch 8.0\nunits', 'a silent series stays out where its line has a value');
39
39
  assert.equal(title(4), 'W5\nAlder 5.0\nBirch, not settled 9.0\nunits', 'and shows where it does not');
40
40
 
41
+ // Lines listed newest first, each with its dashed rest: the unsettled value comes last.
42
+ const years = lines({ ...spec, series: [series[1], series[2], series[0]] }, 600).marks.at(-1);
43
+ assert.equal(years.channels.title.value(rows[4]), 'W5\nAlder 5.0\nBirch, not settled 9.0\nunits', 'an unsettled value after the settled ones');
44
+
41
45
  const legend = renderPlot(lines({ ...spec, legend: true }, 600));
42
46
  assert.ok(!/>Alder</.test(legend), 'with a legend the lines carry no names');
43
47