Skip to content

Scatterplot Matrix ​

A scatterplot matrix of four penguin measurements. Each cell is a chart nested in a band of the grid, plotting its own pair of fields, so its scales are independent of the other cells. The field names of the rows stand vertically, so that they take little room on the left. After G2.

js
const penguins = await d3.csv("/data/penguins.csv", d3.autoType);
const fields = ["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "body_mass_g"];

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

root
  .data(d3.cross(fields, fields))
  .transform(cm.encode, {x: ([fx]) => fx, y: ([, fy]) => fy})
  .transform(cm.spreadX, {domain: fields})
  .transform(cm.spreadY, {domain: fields})
  .transform(cm.plane, {
    x: {label: null, tickSize: 0},
    y: {label: null, tickSize: 0, tickRotate: -90},
  })
  .append(cm.g)
  .data(([fx, fy]) =>
    penguins
      .map((d) => ({x: d[fx], y: d[fy], species: d.species}))
      .filter((d) => Number.isFinite(d.x) && Number.isFinite(d.y)),
  )
  .transform(cm.encode, {x: "x", y: "y", fill: "species"})
  .transform(cm.plane, {
    resolve: {x: "independent", y: "independent"},
    x: {axis: "bottom", grid: true},
    y: {axis: "left", grid: true},
  })
  .add(cm.annotate(cm.rect), {fill: "none", stroke: "currentColor"})
  .add(cm.circle, {r: 1.5});

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