Skip to content

Nested Unit Chart ​

The Titanic's passengers by class, then by survival, then by sex, one dot each. Each level is a chart nested in the bands of the one before, whose bands are proportional to their passengers with flex, so the dots have about the same size everywhere. After G2.

js
const passengers = d3.sort(
  await d3.csv("/data/titanic3.csv", d3.autoType),
  (d) => d.survived,
  (d) => d.sex,
);
const survival = (d) => (d.survived ? "Yes" : "No");

const renderer = cm.svg({width: 640, height: 640});
const root = cm.flow().renderer(renderer);

root
  .data(d3.groups(passengers, (d) => d.pclass))
  .transform(cm.encode, {y: ([pclass]) => pclass, n: ([, rows]) => rows.length})
  .transform(cm.spreadY, {padding: 0.05, flex: "n", domain: [1, 2, 3]})
  .transform(cm.plane, {y: {label: "pclass", tickSize: 0}})
  .append(cm.g)
  .data(([, rows]) => d3.groups(rows, survival))
  .transform(cm.encode, {x: ([s]) => s, n: ([, rows]) => rows.length})
  .transform(cm.spreadX, {padding: 0.05, flex: "n", domain: ["Yes", "No"]})
  .transform(cm.plane, {x: {axis: "bottom"}})
  .append(cm.g)
  .data(([, rows]) => d3.groups(rows, (d) => d.sex))
  .transform(cm.encode, {y: ([sex]) => sex, n: ([, rows]) => rows.length})
  .transform(cm.spreadY, {padding: 0.05, flex: "n"})
  .transform(cm.plane, {y: {axis: "left"}})
  .append(cm.g)
  .data(([, rows]) => rows)
  .transform(cm.encode, {fill: survival})
  .transform(cm.plane, {fill: {domain: ["Yes", "No"]}})
  .transform(cm.pack)
  .add(cm.annotate(cm.rect), {fill: "none", stroke: "currentColor"})
  .add(cm.circle, cm.inset("7.5%"));

root.render();
document.body.append(renderer.node());