Skip to content

Data Transforms ​

Data transforms go between cm.encode and the coordinate system. They read the encoded channels and rewrite the rows: grouping and binning reduce them, stacking and spreading place them in data space, and folding and units make new rows. They are adapted from Observable Plot's transforms, with spreads and units after G2 and GoFish. Each throws "missing channel: x" (or the channel it needs) if no row binds it.

js
const athletes = await d3.csv("/data/athletes.csv", d3.autoType);

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

root
  .data(athletes)
  .transform(cm.encode, {x: "weight", fill: "sex"})
  .transform(cm.binX, {y: "count"})
  .transform(cm.stackY)
  .transform(cm.plane, {y: {grid: true}, fill: {legend: true}})
  .add(cm.rect, cm.insetX(0.5))
  .add(cm.annotate(cm.link), {y: 0});

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

cm.groupX([outputs]) ​

Groups the rows by x and by series, the first of z, fill and stroke that isn't an output, and turns each group into one row. outputs maps a channel to its reducer and defaults to {y: "count"}, such as the bars of a bar chart of counts. A reducer is a name, case-insensitive, or a function:

  • count: the number of rows of the group;
  • sum, mean, median, min, max: of the values of the channel of the same name;
  • first, last: the value of the first or last row;
  • a function, given the values of the channel, or the rows of the group if the channel isn't bound.

A named reducer other than count needs its channel, such as {y: "sum"} needs y. The groups keep their order of first appearance. The channels grouped by keep their values, and others are dropped. The datum of a new row is the array of its group's rows, and a count is labeled "Frequency". key and groupKey are kept if every row of the group shares them. The channel grouped by can't be an output.

js
flow
  .transform(cm.encode, {x: "species"})
  .transform(cm.groupX, {y: "count"})
  .transform(cm.spreadX)

cm.groupY([outputs]) ​

Like cm.groupX, but groups by y, with outputs {x: "count"} by default.

cm.group([outputs]) ​

Like cm.groupX, but groups by x and y, with outputs {fill: "count"} by default, such as the cells of a heatmap.

cm.binX([options]) ​

Bins the rows on x, and groups them by y, if it's bound and isn't an output, and by series. Each non-empty bin becomes one row, whose x and x1 are the bin's lower and upper edges. The other options are outputs, reduced as in cm.groupX, {y: "count"} by default, such as the bars of a histogram. An output on a position gets a baseline of 0 in its pair, such as y1, so bars span from 0; cm.stackY replaces both. The edges are shared by all groups of the flow, so that facets compare.

  • thresholds: the bins, "auto" by default, Scott's rule with at most 200 bins; "scott", "sturges", "freedman-diaconis", a count, an array of thresholds or a d3 threshold function. An unknown name throws "unknown thresholds".
  • interval: the width of the bins, starting at its multiples, instead of thresholds.

cm.binY([options]) ​

Like cm.binX, but bins on y, with outputs {x: "count"} by default.

cm.bin([options]) ​

Like cm.binX, but bins on x and y, with outputs {fill: "count"} by default, such as the cells of a binned heatmap.

cm.stackY([options]) ​

Stacks y: the rows of each x are stacked in order, one running sum for negative values and one for the others, and each row spans from y1, its base, to y, its top, such as stacked columns or stacked areas. Rows without a value are skipped.

If y has bands, from an earlier cm.spreadY, the bands are split among the series instead, so that they sit side by side: a stack after a spread on the same position is a grouped chart. A series missing from a band keeps its slot.

  • order: the order of the series in each stack. By default, the input order, or the order of the series recorded by an earlier transform. "value", "z", "sum", "appearance", "inside-out", any of them prefixed with - to descend, the name of a bound channel, or an array of the series, which also becomes the domain of the series, so that colors follow it. null keeps the input order.
  • reverse: reverses the order, false by default.
  • offset: "normalize" (or "expand") rescales each stack to [0, 1]; "center" (or "silhouette") aligns the middles of the stacks, such as a funnel; "wiggle" shifts the stacks to minimize the changes of slope, such as a streamgraph, with order "inside-out" by default. An unknown offset throws "unknown offset".
  • chunk: wraps equal values, such as the units of cm.unitY, in rows of chunk, like the cells of a waffle. Within a row, each value takes one of chunk columns of its band on x, if it has one.
  • padding: the gaps between the cells of chunks, as a fraction, 0.1 by default.
js
const data = await d3.csv("/data/population-state-age.csv", d3.autoType);
const ages = Array.from(new Set(data.map((d) => d.age)));

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

root
  .data(data.filter((d) => ["CA", "TX", "NY", "FL"].includes(d.state)))
  .transform(cm.encode, {x: "state", y: "population", fill: "age"})
  .transform(cm.spreadX)
  .transform(cm.stackX, {order: ages}) // x has bands: grouped columns
  .transform(cm.plane, {y: {tickFormat: "s", grid: true}, fill: {legend: true}})
  .add(cm.rect);

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

cm.stackX([options]) ​

Like cm.stackY, but stacks x per y, from x1 to x, such as stacked bars or a pie in cm.polar. After cm.spreadX, it splits the bands of x among the series, for grouped columns.

cm.stackEnter([options]) ​

Stacks the entrances of the rows along time, like G2's stackEnter: groups of rows enter one after another, and the rows of a group step after one another. It only arranges the rows; cm.plane and cm.polar compute the delays once they have scaled the encoded timings, so it needs a flow with a transition.

  • by: the name of the channel that groups the rows, by default the series (z, else fill, else stroke); null for one group.
  • order: an array of the values of the groups, in order; by default, the order of first appearance, or the domain of the series.
  • reverse: reverses the order of the groups, false by default.
  • step: the milliseconds between the rows of a group, 0 by default.
  • gap: the milliseconds between a group's end and the next one's start, 0 by default.
  • duration: the duration of each row, unless enterDuration is encoded; by default, the flow's.

It reads its channel as it is, so it goes before the transforms that rewrite it, such as cm.stackX for grouped bars.

Timings are a scale too. Encoded timings, such as {enterDelay: "start", enterDuration: "length"}, are milliseconds, unless their scale, named time by default, has a range: {time: {range: [0, 3000]}} plays them from 0 to the largest in 3s, and {time: {domain: [0, 1], range: [0, 600]}} at 600ms per unit. A timing can name another scale with {value, scale}.

js
flow
  .transform(cm.encode, {x: "category", y: "value", fill: "position"})
  .transform(cm.stackEnter, {step: 100, gap: 200, duration: 300})
  .transform(cm.spreadX)
  .transform(cm.stackX)
  .transform(cm.plane)
  .add(cm.rect, {appear: true, enter: {clipTop: 1}});

See Nightingale entrance.

cm.stackExit([options]) ​

Like cm.stackEnter, but for exits, with exitDuration.

cm.spreadX([options]) ​

Places each category of x in a band, from x to x1, like a d3 band scale, such as the columns of a bar chart. y gets a baseline of 0 in y1 if it's numeric and y1 isn't bound. The axis of x then labels the categories.

  • padding: the padding of the bands, inner and outer, 0.1 by default.
  • paddingInner, paddingOuter: each padding, padding by default.
  • align: how the outer padding is shared, 0.5 by default.
  • sort: the order of the categories, ascending by default; false for the order of the rows; or the name of a channel, such as "y", to order by its maximum, descending with "-y".
  • domain: the categories, in order, instead of sorting them.
  • flex: the name of a channel whose sum over each category sets the width of its band, such as the columns of a Marimekko chart.
  • chunk: instead of categories, puts the rows in slots, chunk rows at a time, grouped by the bands they already share; no channel is needed.

Spread again, a position that already has bands subdivides each row's band into slots, one per row, such as the squares of a waffle row in the band of its category:

js
flow
  .transform(cm.encode, {x: "lake", y: "count", fill: "species"})
  .transform(cm.spreadX) // a band per lake
  .transform(cm.unitY) // a row per unit of count
  .transform(cm.spreadY, {chunk: 5}) // rows of 5 units
  .transform(cm.spreadX) // each unit in its slot of the lake's band
  .transform(cm.plane, {y: {axis: null}})
  .add(cm.rect);

cm.spreadY([options]) ​

Like cm.spreadX, for the categories of y, such as the bars of a horizontal bar chart. Categories in bands go down from the top.

cm.unitY([options]) ​

Turns the rows into one row per unit, such as the squares of a waffle. The rows are grouped by x and by series; the amount of a group is the sum of its y, else its number of rows, and it gets round(|amount| / unit) rows, each with y set to ±unit and the other channels of the group's first row. The datum of each is the rows of its group. Then stack or spread them, such as with cm.stackY({chunk}).

  • unit: the amount a row stands for, 1 by default.
  • order: orders the units of each group by series, as in cm.stackY.

cm.unitX([options]) ​

Like cm.unitY, along x, grouped by y.

cm.fold(options) ​

Folds fields of each row into rows of their own, like Vega-Lite's fold. With {x: fields}, a row becomes one row per field, whose x is the name of the field and y its value, such as the dimensions of parallel coordinates; with {y: fields}, the other way. The names of the fields are the categories of x, in order. Each new row keeps its datum, the row it came from, and the channels encoded before, such as a stroke; z, unless encoded, is the row it came from, so a line goes through the fields of each row. Giving both x and y, or neither, throws.

js
flow
  .transform(cm.encode, {stroke: "species"})
  .transform(cm.fold, {x: ["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm"]})
  .transform(cm.plane, {y: {by: "x"}}) // a scale per field
  .add(cm.lineY);

See Parallel coordinates.

cm.pack([options]) ​

Packs the rows of each group into a grid of square cells that fills its frame, like G2's pack, row by row from the bottom left, in input order. Each row gets its cell as x, x1, y and y1, in pixels. It reads the frame, so it goes after cm.plane, typically in a chart nested in the bands of another, such as the dots of a unit chart in each facet.

  • share: if true, every grid is laid out for the largest count, so that frames of the same size get the same cells; false by default.
js
flow
  .transform(cm.encode, {x: ([pclass]) => pclass})
  .transform(cm.spreadX)
  .transform(cm.plane)
  .append(cm.g)
  .data(([, rows]) => rows)
  .transform(cm.encode, {fill: (d) => (d.survived ? "Yes" : "No")})
  .transform(cm.plane)
  .transform(cm.pack)
  .add(cm.circle, cm.inset("7.5%"));

See Nested unit chart.