Legend Filter
The population by age of the ten most populous states, as stacked columns, with a legend that filters: the ages chosen in the legend are a selection that the data reads, so only those stay in the stacks, which are stacked again from 0. The domain of the colors is every age, so that the legend keeps them all. Click ages in the legend to keep them; double-click to show every age.
js
// The population by age of the ten most populous states, from Plot's grouped bar chart example.
const population = await d3.csv("/data/population-state-age.csv", d3.autoType);
const totals = d3.rollup(
population,
(rows) => d3.sum(rows, (d) => d.population),
(d) => d.state,
);
const states = new Set(
d3
.sort(totals, ([, v]) => -v)
.slice(0, 10)
.map(([state]) => state),
);
const ages = Array.from(new Set(population.map((d) => d.age)));
const data = population.filter((d) => states.has(d.state));
const chosen = cm.selection();
const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow().renderer(renderer);
root
.data(() => data.filter((d) => chosen.test({datum: d}, {empty: true})))
.transform(cm.encode, {x: "state", y: "population", fill: "age", key: (d) => `${d.state} ${d.age}`})
.transform(cm.spreadX)
.transform(cm.stackY, {order: ages})
.transform(cm.plane, {y: {tickFormat: "s"}, fill: {domain: ages, legend: true}})
.add(cm.rect)
.add(cm.legend, {fill: {as: chosen}});
root.render();
document.body.append(renderer.node());