@n1kname/charts 0.3.0 → 0.5.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.5.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
@@ -1,11 +1,13 @@
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
1
+ // Bars on one axis, one per row: a single value, a few series stacked in the order given,
2
+ // bottom to top, or with `grouped` side by side, such as last year beside this one. Returns Plot options without a style, so the same chart draws at build time
3
3
  // (renderPlot) or in the browser (Plot.plot with the page's style).
4
4
  //
5
5
  // Rows are wide: one object per x, a number (or null for none) per series key. Positive
6
6
  // values stack up from zero and negative ones down, so a month that returned more than it
7
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.
8
+ // for figures that are not settled yet; say what each means in a Legend. A run of steps can be
9
+ // set apart as one shaded block with a word on why (`shade`), and a series can carry a short
10
+ // `tag` over its first bar, so two series are not told apart by colour alone.
9
11
 
10
12
  import * as Plot from '@observablehq/plot';
11
13
  import { chrome, tipStyle } from './theme.mjs';
@@ -35,9 +37,23 @@ export const bars = (
35
37
  title,
36
38
  // The gap between bars, as a share of each bar's room.
37
39
  padding = 0.28,
40
+ // How many ems an x label may run before it wraps onto another line, for long labels on
41
+ // a narrow chart. Gets the width.
42
+ wrap = () => Infinity,
43
+ // Words on the y axis, such as its unit, when the chart has no subtitle to say it, and the
44
+ // decimals its labels show.
45
+ yLabel = null,
46
+ yDigits = 0,
47
+ marginLeft = 44,
48
+ marginBottom = 30,
49
+ // The series side by side in each step, each bar from zero, instead of stacked.
50
+ grouped = false,
51
+ // A run of steps set apart: { from, to, text }, the first and last x and why.
52
+ shade = null,
38
53
  },
39
54
  width,
40
55
  ) => {
56
+ const marginRight = 4;
41
57
  const has = (r, key) => typeof r[key] === 'number';
42
58
  // Where each series' piece of each bar starts and ends.
43
59
  const pieces = series.map(() => []);
@@ -47,23 +63,39 @@ export const bars = (
47
63
  series.forEach((s, i) => {
48
64
  if (!has(r, s.key)) return;
49
65
  const v = r[s.key];
50
- const from = v >= 0 ? up : down;
66
+ const from = grouped ? 0 : v >= 0 ? up : down;
51
67
  if (v >= 0) up += v;
52
68
  else down += v;
53
69
  pieces[i].push({ row: r, y1: from, y2: from + v });
54
70
  });
55
71
  }
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);
72
+ const valuesOf = (r) => series.filter((s) => has(r, s.key)).map((s) => r[s.key]);
73
+ const sum = (vs) => vs.reduce((a, b) => a + b, 0);
74
+ const top = (r) => (grouped ? Math.max(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v > 0)));
75
+ const bottom = (r) => (grouped ? Math.min(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v < 0)));
58
76
  const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
59
77
  const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
60
78
  const domain = [
61
79
  y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
62
80
  y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
63
81
  ];
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'));
82
+ // Stacked, the tooltip lists the parts from the top, as they are drawn; grouped, in order.
83
+ const listed = grouped ? series : [...series].reverse();
84
+ const says = title ?? ((r) => [r[x], ...listed.filter((s) => has(r, s.key)).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
85
+ // Grouped, every step has a tooltip, even one with no bars, so a step left out can say why.
86
+ const tipped = grouped ? rows : drawn;
87
+
88
+ // Where the bars sit in a step. Plot's band scale puts `padding` of a step on each side of
89
+ // the bands, so a step is the range over the number of rows plus that padding. Grouped, the
90
+ // scale is not rounded to whole pixels, so the bars land where this says.
91
+ const step = (width - marginLeft - marginRight) / (rows.length + padding);
92
+ const band = step * (1 - padding);
93
+ const GAP = 2;
94
+ const barWidth = Math.min(14, (band - GAP * (series.length - 1)) / series.length);
95
+ const group = barWidth * series.length + GAP * (series.length - 1);
96
+ // Each series' bar, from the left of its band.
97
+ const left = (i) => (band - group) / 2 + i * (barWidth + GAP);
98
+ const inset = (i) => (grouped ? { insetLeft: left(i), insetRight: band - left(i) - barWidth } : {});
67
99
 
68
100
  // Settled rows and dashed ones are separate marks, because a dash cannot vary per bar.
69
101
  const piece = (s, i, rowsOf, edge) =>
@@ -76,24 +108,66 @@ export const bars = (
76
108
  stroke: edge ? s.color : 'var(--c-surface)',
77
109
  strokeWidth: 1,
78
110
  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 } : {}),
111
+ // The last series is the top of the bar: rounded there, square on the baseline. Grouped,
112
+ // every bar is its own top.
113
+ ...(grouped || i === series.length - 1 ? { ry1: 4 } : {}),
114
+ ...inset(i),
81
115
  });
82
116
 
117
+ // The shaded run, edge to edge across its steps, with its word in the middle.
118
+ const shaded = shade ? rows.slice(rows.findIndex((r) => r[x] === shade.from), rows.findIndex((r) => r[x] === shade.to) + 1) : [];
119
+ const shading = shaded.length
120
+ ? [
121
+ Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, inset: -(step - band) / 2 }),
122
+ Plot.text([shaded[0]], {
123
+ x,
124
+ frameAnchor: 'middle',
125
+ dx: ((shaded.length - 1) * step) / 2,
126
+ text: () => shade.text,
127
+ fill: 'var(--c-text-secondary)',
128
+ fontSize: 11,
129
+ }),
130
+ ]
131
+ : [];
132
+
133
+ // A series' tag over its first bar. The first grows leftward from its bar's right edge and
134
+ // the rest rightward from their left edge, so two tags never touch.
135
+ const tags = series.flatMap((s, i) => {
136
+ const first = rows.find((r) => has(r, s.key));
137
+ if (!s.tag || !first) return [];
138
+ const edge = grouped ? (i === 0 ? left(i) + barWidth : left(i)) - band / 2 : 0;
139
+ return [
140
+ Plot.text([first], {
141
+ x,
142
+ y: (r) => (grouped ? Math.max(0, r[s.key]) : top(r)),
143
+ text: () => s.tag,
144
+ dx: edge,
145
+ dy: -6,
146
+ lineAnchor: 'bottom',
147
+ textAnchor: grouped && i === 0 ? 'end' : 'start',
148
+ fill: 'var(--c-text-secondary)',
149
+ fontSize: 10,
150
+ }),
151
+ ];
152
+ });
153
+
154
+ const labels = (v, i) => tick(v, i, width);
83
155
  return {
84
156
  width,
85
157
  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) },
158
+ marginTop: values || series.some((s) => s.tag) ? 24 : 10,
159
+ marginLeft,
160
+ marginRight,
161
+ marginBottom,
162
+ x: { type: 'band', domain: rows.map((r) => r[x]), padding, ...(grouped ? { round: false } : {}), label: null, tickSize: 0, tickFormat: labels, axis: null },
163
+ y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
92
164
  opacity: { type: 'identity' },
93
165
  marks: [
166
+ Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
167
+ ...shading,
94
168
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
95
169
  // 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 })),
170
+ Plot.barY(tipped, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
97
171
  ...series.flatMap((s, i) => [
98
172
  piece(s, i, pieces[i].filter((p) => !dashed(p.row)), false),
99
173
  piece(s, i, pieces[i].filter((p) => dashed(p.row)), true),
@@ -101,8 +175,9 @@ export const bars = (
101
175
  ...(values
102
176
  ? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12 })]
103
177
  : []),
178
+ ...tags,
104
179
  Plot.ruleY([0], { stroke: chrome.axis }),
105
- Plot.tip(drawn, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
180
+ Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
106
181
  ],
107
182
  };
108
183
  };
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,50 @@ 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
+ const small = renderPlot(bars({ ...long, rows: [{ k: 'A', v: 0.3 }, { k: 'B', v: 1.2 }], yDigits: 2 }, 300));
75
+ assert.ok(/>0\.40</.test(small) && !/>1</.test(small), 'small values keep their decimals on the y axis');
76
+
77
+ // Grouped: last year beside this one, each bar from zero, a run of steps shaded.
78
+ const pairs = [
79
+ { m: 'M1', old: 30, now: 20 },
80
+ { m: 'M2', old: 10, now: 12 },
81
+ { m: 'M3', old: null, now: null },
82
+ { m: 'M4', old: null, now: null },
83
+ { m: 'M5', old: 5, now: null },
84
+ ];
85
+ const two = [
86
+ { key: 'old', label: 'Then', color: 'var(--c-chart-2)', tag: '’24' },
87
+ { key: 'now', label: 'Now', color: 'var(--c-chart-1)', tag: '’25' },
88
+ ];
89
+ const g = bars({ rows: pairs, x: 'm', series: two, unit: 'units', grouped: true, shade: { from: 'M3', to: 'M4', text: 'left out' } }, 500);
90
+ const gSvg = renderPlot(g);
91
+ assert.deepEqual(g.y.domain, [0, 30], 'grouped, the y domain holds the highest bar, not a sum');
92
+ const [oldBars, , nowBars] = g.marks.slice(5);
93
+ assert.deepEqual([oldBars.data[0].y1, oldBars.data[0].y2, nowBars.data[0].y1, nowBars.data[0].y2], [0, 30, 0, 20], 'each bar stands on zero');
94
+ // The two bars of a step side by side, 2px apart, centred in the step and no wider than 14px.
95
+ // Each bar's left and right edge: the least and greatest x its path visits.
96
+ const rects = (color) => [...gSvg.matchAll(new RegExp(`fill="var\\(--c-${color}\\)"[^>]*>((?:<path[^>]*>)+)`, 'g'))]
97
+ .flatMap((m) => [...m[1].matchAll(/ d="([^"]+)"/g)])
98
+ .map(([, d]) => {
99
+ const xs = [...d.matchAll(/(?:[MLH]|0 0 1 )([\d.]+)/g)].map((n) => Number(n[1]));
100
+ return [Math.min(...xs), Math.max(...xs)];
101
+ });
102
+ const [o1, n1] = [rects('chart-2')[0], rects('chart-1')[0]];
103
+ assert.ok(o1 && n1, 'both bars of the first step are drawn');
104
+ assert.ok(Math.abs(n1[0] - o1[1] - 2) < 0.01, 'the second bar starts 2px after the first ends');
105
+ assert.ok(o1[1] - o1[0] <= 14.001, 'no bar is wider than 14px');
106
+ assert.ok(gSvg.includes('>left out<'), 'the shaded run says why');
107
+ assert.ok(gSvg.includes('>’24<') && gSvg.includes('>’25<'), 'each series carries its tag over its first bar');
108
+ const gTip = g.marks.at(-1);
109
+ assert.equal(gTip.data.length, 5, 'grouped, every step has a tooltip, even an empty one');
110
+ assert.equal(gTip.channels.title.value(pairs[0]), 'M1\nThen 30\nNow 20\nunits', 'grouped, the tooltip lists the series in order');
111
+ assert.equal(gTip.channels.title.value(pairs[2]), 'M3\nunits', 'an empty step says only its label and unit, not 0');
112
+ assert.ok(!renderPlot(bars({ ...spec, grouped: false }, 600)).includes('left out'), 'no shade unless asked');
113
+
67
114
  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');