@n1kname/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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1kname/charts",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -9,7 +9,8 @@
9
9
  "./plot": "./src/plot.mjs",
10
10
  "./theme": "./src/theme.mjs",
11
11
  "./lines": "./src/lines.mjs",
12
- "./bars": "./src/bars.mjs"
12
+ "./bars": "./src/bars.mjs",
13
+ "./heatmap": "./src/heatmap.mjs"
13
14
  },
14
15
  "dependencies": {
15
16
  "@observablehq/plot": "0.6.17",
@@ -28,6 +29,6 @@
28
29
  "src"
29
30
  ],
30
31
  "scripts": {
31
- "check": "node src/donut.test.mjs && node src/lines.test.mjs && node src/bars.test.mjs"
32
+ "check": "node src/donut.test.mjs && node src/lines.test.mjs && node src/bars.test.mjs && node src/heatmap.test.mjs"
32
33
  }
33
34
  }
package/src/bars.mjs CHANGED
@@ -35,6 +35,13 @@ export const bars = (
35
35
  title,
36
36
  // The gap between bars, as a share of each bar's room.
37
37
  padding = 0.28,
38
+ // How many ems an x label may run before it wraps onto another line, for long labels on
39
+ // a narrow chart. Gets the width.
40
+ wrap = () => Infinity,
41
+ // Words on the y axis, such as its unit, when the chart has no subtitle to say it.
42
+ yLabel = null,
43
+ marginLeft = 44,
44
+ marginBottom = 30,
38
45
  },
39
46
  width,
40
47
  ) => {
@@ -80,17 +87,19 @@ export const bars = (
80
87
  ...(i === series.length - 1 ? { ry1: 4 } : {}),
81
88
  });
82
89
 
90
+ const labels = (v, i) => tick(v, i, width);
83
91
  return {
84
92
  width,
85
93
  height,
86
94
  marginTop: values ? 24 : 10,
87
- marginLeft: 44,
95
+ marginLeft,
88
96
  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) },
97
+ marginBottom,
98
+ x: { type: 'band', domain: rows.map((r) => r[x]), padding, label: null, tickSize: 0, tickFormat: labels, axis: null },
99
+ y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, 0) },
92
100
  opacity: { type: 'identity' },
93
101
  marks: [
102
+ Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
94
103
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
95
104
  // The bar under the pointer, behind the bars.
96
105
  Plot.barY(drawn, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
package/src/bars.test.mjs CHANGED
@@ -34,7 +34,8 @@ assert.deepEqual(ticks, ['M1', 'M3', 'M5'], 'only the ticks the tick function pr
34
34
  assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
35
35
 
36
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);
37
+ // After the x axis, the grid and the pointer's highlight: each series, settled then dashed.
38
+ const [ashSolid, , beechSolid, , cedarSolid, cedarDashed] = options.marks.slice(3);
38
39
  const span = (mark, i) => [mark.data[i].y1, mark.data[i].y2];
39
40
  assert.deepEqual(span(beechSolid, 0), [10, 14], 'a series stacks on the one before it');
40
41
  assert.deepEqual(span(cedarSolid, 0), [14, 16], 'and the last on top');
@@ -64,4 +65,11 @@ const single = bars({ rows: rows.map((r) => ({ year: r.month, v: r.a + r.month.l
64
65
  const labels = [...renderPlot(single).matchAll(/<text[^>]*>(\d+)<\/text>/g)].map((m) => m[1]);
65
66
  assert.deepEqual(labels.slice(-5), ['12', '12', '12', '12', '12'], 'with values, each bar carries its total');
66
67
 
68
+ // Long labels wrap on a narrow chart, and the y axis can carry words.
69
+ const long = { rows: [{ k: 'Before the works', v: 3 }, { k: 'After', v: 2 }], x: 'k', series: [{ key: 'v', label: 'V', color: 'var(--c-chart-1)' }], unit: 'u', yLabel: 'units a year' };
70
+ const wrapped = renderPlot(bars({ ...long, wrap: () => 5 }, 300));
71
+ assert.ok(!/>Before the works</.test(wrapped) && /Before/.test(wrapped), 'a long label wraps onto more lines');
72
+ assert.ok(/>Before the works</.test(renderPlot(bars(long, 300))), 'without wrap it stays on one line');
73
+ assert.ok(/units a year/.test(wrapped), 'the y axis carries its words');
74
+
67
75
  console.log('bars: all assertions pass');
@@ -0,0 +1,49 @@
1
+ // A grid of cells, one per x and y, coloured by a value in steps: hours across, days or
2
+ // nights down. 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
+ // Cells are long: one object per cell, with its x, its y and its value. A cell with no value
6
+ // is left out (Plot draws nothing for it), so its place stays empty rather than looking like
7
+ // the lowest step. The rows
8
+ // set the height, so a chart with more rows is taller instead of more cramped.
9
+
10
+ import * as Plot from '@observablehq/plot';
11
+ import { sequential, tipStyle } from './theme.mjs';
12
+
13
+ // How tall a heatmap of this many rows is, for a page that holds the space before it draws.
14
+ export const heatmapHeight = (rows, rowHeight = 30) => rows * rowHeight + 44;
15
+
16
+ export const heatmap = (
17
+ {
18
+ cells,
19
+ x,
20
+ y,
21
+ value,
22
+ // Every x and y in order, including any with no cells.
23
+ xDomain,
24
+ yDomain,
25
+ // Where each colour step starts: one fewer than the colours.
26
+ steps,
27
+ colors = sequential,
28
+ rowHeight = 30,
29
+ // The tooltip's text per cell.
30
+ title,
31
+ // The labels on each axis. xTick gets (value, index, width).
32
+ xTick = (v) => v,
33
+ yTick = (v) => v,
34
+ marginLeft = 56,
35
+ },
36
+ width,
37
+ ) => ({
38
+ width,
39
+ height: heatmapHeight(yDomain.length, rowHeight),
40
+ marginLeft,
41
+ marginRight: 0,
42
+ marginTop: 8,
43
+ marginBottom: 30,
44
+ padding: 0.06,
45
+ x: { domain: xDomain, label: null, tickSize: 0, tickFormat: (v, i) => xTick(v, i, width) },
46
+ y: { domain: yDomain, label: null, tickSize: 0, tickFormat: yTick },
47
+ color: { type: 'threshold', domain: steps, range: colors },
48
+ marks: [Plot.cell(cells, { x, y, fill: value, tip: tipStyle, title })],
49
+ });
@@ -0,0 +1,46 @@
1
+ // Synthetic data only, like everything in this repo.
2
+ import assert from 'node:assert/strict';
3
+ import { heatmap, heatmapHeight } from './heatmap.mjs';
4
+ import { renderPlot } from './plot.mjs';
5
+ import { sequential } from './theme.mjs';
6
+
7
+ const HOURS = [20, 21, 22, 23];
8
+ const DAYS = ['D1', 'D2', 'D3'];
9
+ const cells = [
10
+ { day: 'D1', hour: 20, level: 500 },
11
+ { day: 'D1', hour: 21, level: 650 },
12
+ { day: 'D2', hour: 22, level: 1300 },
13
+ { day: 'D3', hour: 23, level: null },
14
+ ];
15
+ const spec = {
16
+ cells,
17
+ x: 'hour',
18
+ y: 'day',
19
+ value: 'level',
20
+ xDomain: HOURS,
21
+ yDomain: DAYS,
22
+ steps: [600, 1000],
23
+ colors: sequential.slice(0, 3),
24
+ title: (c) => `${c.day} ${c.hour}:00\n${c.level} units`,
25
+ xTick: (h, _i, width) => (width < 300 && h % 2 ? '' : `${h}h`),
26
+ };
27
+
28
+ const options = heatmap(spec, 400);
29
+ const svg = renderPlot(options);
30
+ assert.equal(options.height, heatmapHeight(3), 'as tall as its rows');
31
+ assert.ok(heatmapHeight(6) > heatmapHeight(3), 'and taller with more rows');
32
+ assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
33
+
34
+ // Each cell takes the colour of the step its value falls in.
35
+ const fills = [...svg.matchAll(/<rect[^>]*fill="(var\(--c-seq-\d\))"/g)].map((m) => m[1]);
36
+ assert.deepEqual(fills, ['var(--c-seq-1)', 'var(--c-seq-2)', 'var(--c-seq-3)'], 'below, between and above the steps');
37
+ assert.equal((svg.match(/<rect/g) ?? []).length, 3, 'a cell with no value is left out');
38
+
39
+ // Labels: every hour on a wide chart, every other on a narrow one.
40
+ const labels = (s) => [...s.matchAll(/>(\d\dh)</g)].map((m) => m[1]);
41
+ assert.deepEqual(labels(svg), ['20h', '21h', '22h', '23h'], 'every x label when there is room');
42
+ assert.deepEqual(labels(renderPlot(heatmap(spec, 280))), ['20h', '22h'], 'fewer when narrow');
43
+
44
+ assert.equal(options.marks[0].channels.title.value(cells[1]), 'D1 21:00\n650 units', "the tooltip's own words");
45
+
46
+ console.log('heatmap: all assertions pass');
package/src/index.mjs CHANGED
@@ -3,3 +3,4 @@ export * from './donut.mjs';
3
3
  export * from './plot.mjs';
4
4
  export * from './lines.mjs';
5
5
  export * from './bars.mjs';
6
+ export * from './heatmap.mjs';
package/src/lines.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // end together, they don't, and a Legend above the chart names them instead.
5
5
  //
6
6
  // Rows are wide: one object per x, a number (or null for no value) per series key. A null
7
- // breaks the line rather than joining across it.
7
+ // breaks the line rather than joining across it. With `time`, x is a Date per row and the
8
+ // steps need not be even, such as weeks with one missing.
8
9
 
9
10
  import * as Plot from '@observablehq/plot';
10
11
  import { chrome, tipStyle } from './theme.mjs';
@@ -27,6 +28,20 @@ export const lines = (
27
28
  // A mark on every point. Leave off for long, dense series.
28
29
  dots = true,
29
30
  legend = false,
31
+ // x as dates on a time scale, labelled at the dates `xTicks` gives for a width.
32
+ time = false,
33
+ xTicks,
34
+ // A line at zero, for values that can fall below it.
35
+ zero = false,
36
+ // Words on the y axis, such as its unit, and the decimals its labels show.
37
+ yLabel = null,
38
+ yDigits = 0,
39
+ // The tooltip's text per row. By default the label, each series with a value, and the unit.
40
+ title: says,
41
+ marginLeft = 44,
42
+ marginTop = 10,
43
+ // Room on the right: by default for the end labels, or a little for the last x label with a legend.
44
+ marginRight = legend ? 8 : 58,
30
45
  },
31
46
  width,
32
47
  ) => {
@@ -42,7 +57,7 @@ export const lines = (
42
57
  ...series.filter((s) => s.silent && s.continues && has(r, s.key) && !has(r, s.continues)),
43
58
  ];
44
59
  const tipped = rows.filter((r) => told(r).length);
45
- const title = (r) => [r[x], ...told(r).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n');
60
+ const title = says ?? ((r) => [r[x], ...told(r).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
46
61
 
47
62
  const named = series
48
63
  .map((s) => ({ s, name: s.endLabel ?? (s.silent ? false : s.label) }))
@@ -51,14 +66,17 @@ export const lines = (
51
66
  return {
52
67
  width,
53
68
  height,
54
- marginTop: 10,
55
- marginLeft: 44,
56
- marginRight: legend ? 8 : 58,
69
+ marginTop,
70
+ marginLeft,
71
+ marginRight,
57
72
  marginBottom: 30,
58
- x: { type: 'point', domain: rows.map((r) => r[x]), label: null, tickSize: 0, tickFormat: (v, i) => tick(v, i, width) },
59
- y: { domain, nice: true, label: null, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, 0) },
73
+ x: time
74
+ ? { type: 'utc', label: null, tickSize: 0, ticks: xTicks?.(width), tickFormat: (v, i) => tick(v, i, width) }
75
+ : { type: 'point', domain: rows.map((r) => r[x]), label: null, tickSize: 0, tickFormat: (v, i) => tick(v, i, width) },
76
+ y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
60
77
  marks: [
61
78
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
79
+ ...(zero ? [Plot.ruleY([0], { stroke: chrome.axis })] : []),
62
80
  ...series.map((s) =>
63
81
  Plot.line(rows, {
64
82
  x,
@@ -68,18 +86,19 @@ export const lines = (
68
86
  strokeDasharray: s.dashed ? '4 3' : undefined,
69
87
  }),
70
88
  ),
71
- ...(dots
72
- ? series.map((s) =>
73
- Plot.dot(rows.filter((r) => has(r, s.key)), {
74
- x,
75
- y: s.key,
76
- r: 2.5,
77
- fill: s.dashed ? 'var(--c-surface)' : s.color,
78
- stroke: s.color,
79
- strokeWidth: s.dashed ? 1.5 : 0,
80
- }),
81
- )
82
- : []),
89
+ // A series' own `dots` wins over the chart's.
90
+ ...series
91
+ .filter((s) => s.dots ?? dots)
92
+ .map((s) =>
93
+ Plot.dot(rows.filter((r) => has(r, s.key)), {
94
+ x,
95
+ y: s.key,
96
+ r: 2.5,
97
+ fill: s.dashed ? 'var(--c-surface)' : s.color,
98
+ stroke: s.color,
99
+ strokeWidth: s.dashed ? 1.5 : 0,
100
+ }),
101
+ ),
83
102
  ...named.map(({ s, name }) => {
84
103
  const last = rows.findLast((r) => has(r, s.key));
85
104
  return Plot.text(last ? [last] : [], {
@@ -48,4 +48,38 @@ assert.ok(!/>Alder</.test(legend), 'with a legend the lines carry no names');
48
48
  const floor = lines({ ...spec, y: [0, 'auto'] }, 600);
49
49
  assert.equal(floor.y.domain[0], 0, 'a fixed end of the y domain is kept');
50
50
 
51
+ // Dates on a time scale, labelled where asked, one series with dots and the other without,
52
+ // a line at zero and the tooltip's own words.
53
+ const days = ['2024-01-01', '2024-01-08', '2024-01-22', '2024-01-29'].map((d, i) => ({ date: new Date(d), a: i < 2 ? i - 0.5 : null, b: i >= 1 ? i : null }));
54
+ const timed = lines(
55
+ {
56
+ rows: days,
57
+ x: 'date',
58
+ time: true,
59
+ xTicks: () => [days[0].date, days[3].date],
60
+ tick: (d) => d.toISOString().slice(5, 10),
61
+ series: [
62
+ { key: 'a', label: 'Ash', color: 'var(--c-chart-2)', dots: false },
63
+ { key: 'b', label: 'Beech', color: 'var(--c-chart-1)' },
64
+ ],
65
+ unit: 'units',
66
+ digits: 1,
67
+ dots: true,
68
+ zero: true,
69
+ yLabel: 'units a week',
70
+ title: (r) => `Week of ${r.date.toISOString().slice(0, 10)}`,
71
+ legend: true,
72
+ },
73
+ 600,
74
+ );
75
+ const timedSvg = renderPlot(timed);
76
+ assert.equal(timed.x.type, 'utc', 'dates go on a time scale');
77
+ assert.deepEqual([...timedSvg.matchAll(/>(\d\d-\d\d)</g)].map((m) => m[1]), ['01-01', '01-29'], 'labelled only at the dates asked for');
78
+ assert.equal((timedSvg.match(/<circle/g) ?? []).length, 3, 'dots only on the series that wants them');
79
+ assert.ok(/<g stroke="var\(--c-chart-axis\)"><line y2="([\d.]+)" y1="\1"/.test(timedSvg), 'a line at zero');
80
+ assert.ok(/units a week/.test(timedSvg), 'the y axis carries its words');
81
+ assert.equal(timed.marks.at(-1).channels.title.value(days[1]), 'Week of 2024-01-08', "the tooltip's own words");
82
+
83
+ assert.equal(lines({ ...spec, legend: true, marginRight: 24 }, 600).marginRight, 24, 'a page can give the last label room');
84
+
51
85
  console.log('lines: all assertions pass');