Bar Chart Race in the Terminal
The bar chart race on the terminal renderer: the top 12 brands by value, one keyframe per year, keyed by name, so that the bars slide to their new ranks cell by cell, and the value labels tick between years. The year is a banner in a figlet font.
js
const brands = await d3.csv("/data/category-brands.csv", d3.autoType);
const n = 12;
const years = d3.groups(brands, (d) => d.date.getUTCFullYear());
const renderer = cm.terminal({width: 640, height: 480, units: "pixels"});
const root = cm.flow({transition: {duration: 1000, ease: "linear"}}).renderer(renderer);
// The labels of a bar, at its end, sliding in and out from below with it.
const label = {padding: 6, enter: {y: 500}, exit: {y: 500}};
function draw() {
const keyframes = root.data(years).append(cm.keyframe);
keyframes.append(cm.text, {
x: 620,
y: 468,
text: ([year]) => year,
fontFamily: "figlet",
textAlign: "end",
textBaseline: "bottom",
fill: "#666",
});
keyframes
.data(([, rows]) => d3.sort(rows, (d) => -d.value).slice(0, n))
.transform(cm.encode, {x: "value", y: "name", fill: "category", key: "name"})
.transform(cm.spreadY, {padding: 0.1, sort: "-x"})
.transform(cm.plane, {
marginTop: 30,
marginLeft: 10,
marginRight: 70,
marginBottom: 0,
resolve: {x: "independent"},
x: {axis: "top", grid: true, label: null},
y: {axis: null},
})
.add(cm.rect, {fillOpacity: 0.7, enter: {y: 500}, exit: {y: 500}})
.add(cm.label, {...label, position: "inside-right", text: "name"})
.add(cm.label, {...label, position: "right", text: "value", format: ",d"});
}
// Plays the keyframes, then plays them again a second after they end.
function play() {
draw();
root.render();
root.finished().then(() => setTimeout(play, 1000));
}
play();
document.body.append(renderer.node());