Skip to content

A Chart as a Mark ​

Small multiples of the sales of each market by segment, with axes along the edges of the grid, like facets. Each cell is a bar chart defined as a mark with cm.mark, as a library of charts would offer it: it brings its own data and encoding, stacks the bars along y, and returns its chart, so it can be appended in the cells of another chart.

js
// A chart of vertical bars as a mark: it makes a chart for each row of its group, of its data,
// or with data as a function, of the data of that row. The options of its cm.plane are plane;
// the other options go to the bars.
const barY = cm.mark((flow, value, {group, options: {data, encode, plane, ...style}}) =>
  flow
    .data((i) => (typeof data === "function" ? data(group[i]) : data))
    .transform(cm.encode, encode)
    .transform(cm.spreadX)
    .transform(cm.stackY)
    .transform(cm.plane, plane)
    .add(cm.rect, style),
);

const sales = await d3.csv("/data/sales.csv", d3.autoType);
const markets = d3.groups(sales, (d) => d.market).map(([market, rows]) => ({market, rows}));

const renderer = cm.svg({height: 300});
const root = cm.flow().renderer(renderer);

root
  .data(markets)
  .transform(cm.encode, {x: "market"})
  .transform(cm.spreadX)
  .transform(cm.plane, {width: "auto", x: {tickSize: 0}})
  .append(barY, {
    data: (d) => d.rows,
    encode: {x: "segment", y: "value", fill: "segment"},
    plane: {x: {axis: null}, y: {axis: "left"}, fill: {legend: true}},
  });

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