@n1kname/charts 0.4.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 +1 -1
- package/src/bars.mjs +84 -18
- package/src/bars.test.mjs +39 -0
package/package.json
CHANGED
package/src/bars.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
// Bars on one axis, one per row: a single value,
|
|
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';
|
|
@@ -38,13 +40,20 @@ export const bars = (
|
|
|
38
40
|
// How many ems an x label may run before it wraps onto another line, for long labels on
|
|
39
41
|
// a narrow chart. Gets the width.
|
|
40
42
|
wrap = () => Infinity,
|
|
41
|
-
// Words on the y axis, such as its unit, when the chart has no subtitle to say it
|
|
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.
|
|
42
45
|
yLabel = null,
|
|
46
|
+
yDigits = 0,
|
|
43
47
|
marginLeft = 44,
|
|
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,
|
|
45
53
|
},
|
|
46
54
|
width,
|
|
47
55
|
) => {
|
|
56
|
+
const marginRight = 4;
|
|
48
57
|
const has = (r, key) => typeof r[key] === 'number';
|
|
49
58
|
// Where each series' piece of each bar starts and ends.
|
|
50
59
|
const pieces = series.map(() => []);
|
|
@@ -54,23 +63,39 @@ export const bars = (
|
|
|
54
63
|
series.forEach((s, i) => {
|
|
55
64
|
if (!has(r, s.key)) return;
|
|
56
65
|
const v = r[s.key];
|
|
57
|
-
const from = v >= 0 ? up : down;
|
|
66
|
+
const from = grouped ? 0 : v >= 0 ? up : down;
|
|
58
67
|
if (v >= 0) up += v;
|
|
59
68
|
else down += v;
|
|
60
69
|
pieces[i].push({ row: r, y1: from, y2: from + v });
|
|
61
70
|
});
|
|
62
71
|
}
|
|
63
|
-
const
|
|
64
|
-
const
|
|
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)));
|
|
65
76
|
const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
|
|
66
77
|
const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
|
|
67
78
|
const domain = [
|
|
68
79
|
y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
|
|
69
80
|
y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
|
|
70
81
|
];
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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 } : {});
|
|
74
99
|
|
|
75
100
|
// Settled rows and dashed ones are separate marks, because a dash cannot vary per bar.
|
|
76
101
|
const piece = (s, i, rowsOf, edge) =>
|
|
@@ -83,26 +108,66 @@ export const bars = (
|
|
|
83
108
|
stroke: edge ? s.color : 'var(--c-surface)',
|
|
84
109
|
strokeWidth: 1,
|
|
85
110
|
strokeDasharray: edge ? '3 2' : undefined,
|
|
86
|
-
// The last series is the top of the bar: rounded there, square on the baseline.
|
|
87
|
-
|
|
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),
|
|
88
115
|
});
|
|
89
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
|
+
|
|
90
154
|
const labels = (v, i) => tick(v, i, width);
|
|
91
155
|
return {
|
|
92
156
|
width,
|
|
93
157
|
height,
|
|
94
|
-
marginTop: values ? 24 : 10,
|
|
158
|
+
marginTop: values || series.some((s) => s.tag) ? 24 : 10,
|
|
95
159
|
marginLeft,
|
|
96
|
-
marginRight
|
|
160
|
+
marginRight,
|
|
97
161
|
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,
|
|
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) },
|
|
100
164
|
opacity: { type: 'identity' },
|
|
101
165
|
marks: [
|
|
102
166
|
Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
|
|
167
|
+
...shading,
|
|
103
168
|
Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
|
|
104
169
|
// The bar under the pointer, behind the bars.
|
|
105
|
-
Plot.barY(
|
|
170
|
+
Plot.barY(tipped, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
|
|
106
171
|
...series.flatMap((s, i) => [
|
|
107
172
|
piece(s, i, pieces[i].filter((p) => !dashed(p.row)), false),
|
|
108
173
|
piece(s, i, pieces[i].filter((p) => dashed(p.row)), true),
|
|
@@ -110,8 +175,9 @@ export const bars = (
|
|
|
110
175
|
...(values
|
|
111
176
|
? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12 })]
|
|
112
177
|
: []),
|
|
178
|
+
...tags,
|
|
113
179
|
Plot.ruleY([0], { stroke: chrome.axis }),
|
|
114
|
-
Plot.tip(
|
|
180
|
+
Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
|
|
115
181
|
],
|
|
116
182
|
};
|
|
117
183
|
};
|
package/src/bars.test.mjs
CHANGED
|
@@ -71,5 +71,44 @@ const wrapped = renderPlot(bars({ ...long, wrap: () => 5 }, 300));
|
|
|
71
71
|
assert.ok(!/>Before the works</.test(wrapped) && /Before/.test(wrapped), 'a long label wraps onto more lines');
|
|
72
72
|
assert.ok(/>Before the works</.test(renderPlot(bars(long, 300))), 'without wrap it stays on one line');
|
|
73
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');
|
|
74
113
|
|
|
75
114
|
console.log('bars: all assertions pass');
|