Skip to content

Why Charming? ​

Two tools shaped how I program: Processing, which makes coding fun, and D3, which makes it elegant. Charming comes from two things I noticed using them, and later building G2.

Generative art and visualization are both data-driven. Generative art is driven by data that algorithms generate, and visualization by data from daily life. Both map rows of data to shapes, yet they live in different tools: p5.js for one, D3, Vega-Lite and Plot for the other. Charming is one tool for both, so that an artist's sketch can grow into a chart and a chart can borrow an artist's shapes.

A new balance between D3 and the grammar of graphics. D3 is open: any shape, any layout, any interaction, but you write the scales, the layout and the joins yourself. Grammars such as Vega-Lite and Observable Plot are concise, but closed: a fixed set of marks, and an operator for each new idea. Charming keeps D3's openness, because its shapes, transforms and renderers are plain functions, and makes a chart as short as a grammar's, because the grammar is a set of those functions.

The rest of this page builds the flow up one property at a time. Each section starts with the core, drawing without the vis layer, then shows what the vis layer makes of it, and compares it with the closest prior work. The examples show more.

Flow is data-driven ​

A flow takes data and appends a shape for each row. Here the rows are the seeds of a sunflower, the numbers 0 to 599, and each option of the circle is a function of its row. The seeds are placed with the golden angle, already in pixels:

js
const golden = Math.PI * (3 - Math.sqrt(5));
const renderer = cm.svg({width: 640, height: 480});
const root = cm.flow().renderer(renderer);

root.data(d3.range(600)).append(cm.circle, {
  x: (i) => 320 + 9 * Math.sqrt(i) * Math.cos(i * golden),
  y: (i) => 240 + 9 * Math.sqrt(i) * Math.sin(i * golden),
  r: (i) => 1 + i / 120,
  fill: "currentColor",
});

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

If you know D3, this is its data join, and nothing new yet:

js
d3.select(svg)
  .selectAll("circle")
  .data(d3.range(600))
  .join("circle")
  .attr("cx", (i) => 320 + 9 * Math.sqrt(i) * Math.cos(i * golden))
  .attr("cy", (i) => 240 + 9 * Math.sqrt(i) * Math.sin(i * golden))
  .attr("r", (i) => 1 + i / 120);

The difference is when it runs. D3 sets the attributes at once. A flow records the steps, and runs them when it renders, so it can run them again, and on any renderer: the rest of this page follows from that.

Flow is transformable ​

Above, the drawing mixes what a seed is with where it goes on the screen: 320 +, 9 *, 1 + i / 120. A transform separates them. cm.bind says what each channel of a seed is, in its own units. cm.fit maps the positions to the canvas, and cm.scale maps the size and the color:

js
const golden = Math.PI * (3 - Math.sqrt(5));
const renderer = cm.svg({width: 480, height: 480});
const root = cm.flow().renderer(renderer);

root
  .data(d3.range(600))
  .transform(cm.bind, {
    x: (i) => Math.sqrt(i) * Math.cos(i * golden),
    y: (i) => Math.sqrt(i) * Math.sin(i * golden),
    r: (i) => i,
    fill: (i) => i,
  })
  .transform(cm.fit, {margin: 20})
  .transform(cm.scale, {r: {range: [1.5, 7]}, fill: {scale: d3.scaleSequential(d3.interpolateYlOrBr)}})
  .append(cm.circle);

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

A transform is a function of a flow's rows and channels, and returns new ones. Nothing in the chain is special: cm.fit is about fifty lines of code, and yours would sit in the same place. The shapes appended after the transforms draw the channels they bound.

Flow is extensible ​

Because transforms are open, the vis layer is just more of them. Here a chart starts. A column chart of fish caught in six lakes: cm.encode binds fields, cm.groupX sums the catch per lake, cm.spreadX gives each lake a band, and cm.plane makes the scales and axes. The rect fills the space it's given:

js
const seafood = await d3.csv("/data/seafood.csv", d3.autoType);
const renderer = cm.svg({width: 640, height: 320});
const root = cm.flow().renderer(renderer);

root
  .data(seafood)
  .transform(cm.encode, {x: "lake", y: "count"})
  .transform(cm.groupX, {y: "sum"})
  .transform(cm.spreadX)
  .transform(cm.plane)
  .add(cm.rect, {fill: "steelblue"});

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

In Plot and Vega-Lite, the bar is a mark that owns its layout: Plot.barY places itself in bands, and "mark": "bar" decides its width. In Charming, as in GoFish (Pollock & Satyanarayan), the layout is an operator, and the rect is just a shape:

ts
chart(seafood)
  .flow(spread({by: "lake", dir: "x"}))
  .mark(rect({h: "count"}))
  .render(container);

So the rect can be placed by other transforms. Stacking the species with cm.stackY gives a stacked bar, and an area between the stacks gives GoFish's ribbon chart:

js
const seafood = await d3.csv("/data/seafood.csv", d3.autoType);
const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow().renderer(renderer);

root
  .data(seafood)
  .transform(cm.encode, {x: "lake", y: "count", fill: "species"})
  .transform(cm.spreadX, {paddingInner: 0.6})
  .transform(cm.stackY, {order: "value"})
  .transform(cm.plane)
  .add(cm.rect)
  .add(cm.areaY, {curve: "bump-x", fillOpacity: 0.6});

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

Cutting each bar into units with cm.unitY, and spreading them again, gives a waffle. And the rect can be replaced: the same flow draws a circle in each cell, or any shape, including your own:

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

function waffle(shape) {
  const renderer = cm.svg({width: 320, height: 320});
  const root = cm.flow().renderer(renderer);
  root
    .data(seafood)
    .transform(cm.encode, {x: "lake", y: "count", fill: "species"})
    .transform(cm.spreadX)
    .transform(cm.unitY)
    .transform(cm.spreadY, {chunk: 5})
    .transform(cm.spreadX)
    .transform(cm.plane, {y: {axis: null}})
    .add(shape);
  root.render();
  return renderer.node();
}

document.body.append(waffle(cm.rect), waffle(cm.circle));

Coordinates are a transform too. Replacing cm.plane with cm.polar bends the ribbon chart around a circle; the rects become arcs and the area a radial area, and nothing else changes:

js
const seafood = await d3.csv("/data/seafood.csv", d3.autoType);
const renderer = cm.svg({width: 640, height: 640});
const root = cm.flow().renderer(renderer);

root
  .data(seafood)
  .transform(cm.encode, {x: "lake", y: "count", fill: "species"})
  .transform(cm.spreadX, {paddingInner: 0.9, paddingOuter: 0.45, align: 0})
  .transform(cm.stackY, {order: "value"})
  .transform(cm.polar, {innerRadius: 0.2, x: {axis: "outer"}, y: {type: "linear", axis: true}})
  .add(cm.arc)
  .add(cm.areaRadial, {curve: "bump-x", fillOpacity: 0.8});

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

At the end of this road, every row is a shape. A unit chart of penguins spreads each island into a band, each band into rows of ten, and each row into its penguins, one rect each:

js
const penguins = await d3.csv("/data/penguins.csv", d3.autoType);
const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow().renderer(renderer);

root
  .data(penguins)
  .transform(cm.encode, {x: "island", fill: "species"})
  .transform(cm.spreadX)
  .transform(cm.spreadY, {chunk: 10})
  .transform(cm.spreadX)
  .transform(cm.plane, {y: {axis: null}})
  .add(cm.rect);

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

GoFish's spread and stack are where these operators come from. What Charming adds is that they are transforms of a flow, like cm.fit, so the same chain also nests, animates and reacts, as the next sections show.

Flow is nested ​

cm.g appends a group to each row, and .data(fn) after it starts a flow in each group, with data computed from its row. In the core, a garden: each row is a plant, its group is translated to its place, and its flow draws its own seeds:

js
const golden = Math.PI * (3 - Math.sqrt(5));
const renderer = cm.svg({width: 640, height: 260});
const root = cm.flow().renderer(renderer);

const plants = root.data(d3.range(10)).append(cm.g, {
  x: (k) => 64 + (k % 5) * 128,
  y: (k) => 65 + Math.floor(k / 5) * 130,
});

const seeds = plants.data((k) => d3.range(20 + k * 20));

seeds.append(cm.circle, {
  x: (i) => 2.6 * Math.sqrt(i) * Math.cos(i * golden),
  y: (i) => 2.6 * Math.sqrt(i) * Math.sin(i * golden),
  r: 1.6,
  fill: "currentColor",
});

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

The flow is written in parts, as D3 code usually is: plants and seeds are flows, and each step returns a new one. The same operator composes charts. The parent's coordinates give each row a frame, and the nested flow is a whole chart, with its own encoding and scales, drawn in it. Here each lake, at its location, is a pie of its catch:

js
const lakes = await d3.csv("/data/seafood-locations.csv", d3.autoType);
const seafood = await d3.csv("/data/seafood.csv", d3.autoType);
const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow().renderer(renderer);

const map = root
  .data(lakes)
  .transform(cm.encode, {x: "x", y: "y"})
  .transform(cm.plane, {margin: 40, marginLeft: 60});

const pie = map.append(cm.g).data((lake) => seafood.filter((d) => d.lake === lake.lake));

pie
  .transform(cm.encode, {x: "count", fill: "species"})
  .transform(cm.stackX)
  .transform(cm.polar, {width: 40, height: 40, resolve: {x: "independent"}})
  .add(cm.arc, {stroke: "white"});

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

Points give glyphs, and bands give facets. Nesting bands in bands, three times, gives a mosaic of the Titanic's passengers, by class, survival and sex, with one circle each:

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);

const classes = 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}});

const survived = classes
  .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"}});

const sexes = survived
  .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"}});

const people = sexes
  .append(cm.g)
  .data(([, rows]) => rows)
  .transform(cm.encode, {fill: survival})
  .transform(cm.plane, {fill: {domain: ["Yes", "No"]}})
  .transform(cm.pack);

people.add(cm.annotate(cm.rect), {fill: "none", stroke: "currentColor"}).add(cm.circle, cm.inset("7.5%"));

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

Layers are the other half of composition. flow.branch splits a flow and joins it again, so the next transform sees every layer: here a dual axis, whose layers share x, and each has its own y, named for its scale.

js
const seattle = await d3.csv("/data/seattle-weather.csv", d3.autoType);
const month = (d) => new Date(Date.UTC(2000, d.date.getUTCMonth()));
const renderer = cm.svg({width: 640, height: 400});
const root = cm.flow().renderer(renderer);

const [temperature, precipitation] = root
  .data(seattle)
  .branch(
    (flow) =>
      flow
        .transform(cm.encode, {x: month, y: {value: "temp_max", scale: "temperature"}, y1: "temp_min"})
        .transform(cm.groupX, {y: "mean", y1: "mean"}),
    (flow) =>
      flow
        .transform(cm.encode, {x: month, y: {value: "precipitation", scale: "precipitation"}})
        .transform(cm.groupX, {y: "mean"}),
  )
  .transform(cm.plane, {
    x: {label: null, tickFormat: d3.utcFormat("%b")},
    temperature: {label: "Avg. Temperature (°C)"},
    precipitation: {label: "Precipitation (inches)", axis: "right"},
  });

temperature.add(cm.areaY, {fill: "#85C5A6", fillOpacity: 0.3});
precipitation.add(cm.lineY, {stroke: "#85A9C5", strokeWidth: 2, curve: "monotone-x"});

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

Prior work composes with more operators:

  • Vega-Lite has four: layer, concat, facet and repeat, each with its own syntax. Charming has two: nesting, for everything placed in another's space, and branch, for layers. Scales resolve as shared or independent, with Vega-Lite's semantics.

  • GoFish is the closest: its graphical operators nest, and a chart can be a mark. GoFish writes the pies above as a chart nested as a mark, which joins each lake's catch:

    ts
    chart(catchLocationsArray, {w: 400, h: 400})
      .flow(scatter({by: "lake", x: "x", y: "y"}))
      .mark(
        chart({coord: Coord.clock()})
          .flow(join(seafood, {on: "lake"}), stack({by: "species", dir: "x", h: 20}))
          .mark(rect({w: "count", fill: "species"})),
      )
      .render(container);
  • Atom (Park et al.), a grammar of unit visualizations, partitions containers recursively, as the mosaic does.

What nesting adds beyond them is that the nested tree is also what animates and reacts.

Flow is composable ​

The charts above are short, but each still spells out its encoding and layout. A grammar packs these into marks, such as Plot's barY. In Charming, a high-level mark is a flow packed into a shape with cm.mark. Below, barY is a whole bar chart: its data, encoding, layout and axes. A chart is then one call, as in Plot. And it doesn't close the flow: its other options go to its rects, and the rule appended to it is drawn in its chart, in its scales:

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

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 renderer = cm.svg({width: 640, height: 360});
const root = cm.flow().renderer(renderer);

const bars = root.append(barY, {
  data: alphabet,
  encode: {x: "letter", y: "frequency"},
  plane: {y: {tickFormat: "%"}},
  fill: "steelblue",
});

bars.add(cm.annotate(cm.link), {y: d3.mean(alphabet, (d) => d.frequency), stroke: "red"});

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

A mark is still a shape, so it nests like one. Appended to the bands of another chart, with data from each band's row, the same barY draws small multiples:

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

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 renderer = cm.svg({height: 300});
const root = cm.flow().renderer(renderer);

const facets = root
  .data(markets)
  .transform(cm.encode, {x: "market"})
  .transform(cm.spreadX)
  .transform(cm.plane, {width: "auto", x: {tickSize: 0}});

facets.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());

In a grammar, an abstraction is a wall. Plot's barY does what its options name, and Vega-Lite's composite marks, such as boxplot, expand into specs you change only through their options. A Charming mark is a function of a flow, so it lets the low level through:

  • its options pass on to its shapes;
  • what's appended to it is drawn in its chart;
  • an author who outgrows it copies its few lines and edits them, without switching libraries.

So high-level libraries can be built on Charming without hiding it. A charming-plot is possible: Plot's API, with barY, lineY, dot, ruleY and plot({marks}), as marks over the vis layer. It would cover the charts that need nothing more, and keep the flow one step below for the ones that do. A domain library, of networks, maps or generative patterns, would work the same way.

Flow is animated ​

A flow can render again. With the transition option, each render animates from what's shown to what the flow draws now: shapes that match by key move, and the others enter and exit. In the core, a button picks a new angle for the sunflower, and the seeds move to their new places, with no transition code:

js
const angles = [137.5, 137.6, 99.5, 222.5, 90];
const renderer = cm.svg({width: 480, height: 480});
const root = cm.flow({transition: {duration: 1500}}).renderer(renderer);
let k = 0;

function draw() {
  const angle = (angles[k] * Math.PI) / 180;
  root
    .data(d3.range(600))
    .transform(cm.bind, {
      x: (i) => Math.sqrt(i) * Math.cos(i * angle),
      y: (i) => Math.sqrt(i) * Math.sin(i * angle),
      r: (i) => i,
      key: (i) => i,
    })
    .transform(cm.fit, {margin: 20})
    .transform(cm.scale, {r: {range: [1.5, 7]}})
    .append(cm.circle, {fill: "currentColor"});
  root.render();
}

const button = document.createElement("button");
button.textContent = "Next angle";
button.onclick = () => ((k = (k + 1) % angles.length), draw());

draw();
document.body.append(button, renderer.node());

In D3, the same update is a join whose enter, update and exit each get a transition by hand:

js
svg
  .selectAll("circle")
  .data(seeds, (d) => d.id)
  .join(
    (enter) => enter.append("circle").attr("r", 0),
    (update) => update,
    (exit) => exit.transition().attr("r", 0).remove(),
  )
  .transition()
  .duration(1500)
  .attr("cx", (d) => x(d))
  .attr("cy", (d) => y(d));

In Charming, an animation is the difference between two renders of the same flow. The same flow drawn as a sequence of cm.keyframes plays from one to the next. Below, the bars are keyed by gender, and the points are grouped by it (groupKey), so each bar splits into one piece per person, and the pieces move to their points:

js
const people = await d3.json("/data/people.json");
const renderer = cm.svg({width: 640, height: 480});
const root = cm.flow({transition: {duration: 1000}}).renderer(renderer);

function draw() {
  root
    .append(cm.keyframe)
    .data(people)
    .transform(cm.encode, {x: "gender", y: "weight", fill: "gender", key: "gender"})
    .transform(cm.groupX, {y: "mean"})
    .transform(cm.spreadX)
    .transform(cm.plane)
    .add(cm.rect);

  root
    .append(cm.keyframe)
    .data(people)
    .transform(cm.encode, {x: "height", y: "weight", fill: "gender", groupKey: "gender"})
    .transform(cm.plane)
    .add(cm.circle, {r: 3, fillOpacity: 0.7});
}

const button = document.createElement("button");
button.textContent = "Replay";
button.onclick = () => (draw(), root.render());

draw();
root.render();
document.body.append(button, renderer.node());

Animated Vega-Lite (Zong, Pollock, Wootton & Satyanarayan) adds time as an encoding channel and tweens the marks that share a key across keyframes. Charming takes another route:

  • No time channel: animation is a diff of scenes, so any change to a flow animates, whether it comes from new data, a signal, a brush or a keyframe.
  • Timing is encoded: delays and durations are channels with a scale of their own. cm.stackEnter stacks them, as it stacks bars.
  • One to many: matching a key to a groupKey makes one-to-many morphs like the one above.

More: bar chart race, bubble sort, shape morph.

Flow is reactive ​

Above, a click built the flow again and rendered it. A signal does without both. A flow reads a signal's value as it runs; when the value changes, only the steps that read it run again, and the flow is drawn again on the next frame. In the core, a slider sets the angle of the sunflower:

js
const angle = cm.signal(137.5);
const renderer = cm.svg({width: 480, height: 480});
const root = cm.flow().renderer(renderer);

root
  .data(d3.range(600))
  .transform(cm.bind, {
    x: (i) => Math.sqrt(i) * Math.cos((i * angle.value * Math.PI) / 180),
    y: (i) => Math.sqrt(i) * Math.sin((i * angle.value * Math.PI) / 180),
    r: (i) => i,
  })
  .transform(cm.fit, {margin: 20})
  .transform(cm.scale, {r: {range: [1.5, 7]}})
  .append(cm.circle, {fill: "currentColor"});

root.render();

const input = Object.assign(document.createElement("input"), {type: "range", min: 130, max: 145, step: 0.05});
input.value = angle.value;
input.oninput = () => (angle.value = +input.value);
document.body.append(input, renderer.node());

This is the model of front-end frameworks, applied to drawing:

  • React runs a component again when its state changes, and diffs the virtual DOM it returns.
  • Vue and Solid track which code read which value, and run only that again. Charming does this per step of a flow: the data, a transform, a shape's options.
  • Then the diff animates: with a transition, what a signal changes moves to its new place, as in §6.

In the vis layer, an interaction is a signal. A selection, cm.selection, is a value whose clauses interactors such as cm.nearestX, cm.brushX and cm.toggle set. Shapes read it, as a filter, or flows read it in plain code. A tooltip is a selection set by cm.nearestX, which a dot and a cm.tip filter by. Hover the lines:

js
const symbols = ["AAPL", "AMZN", "GOOG", "IBM"];
const tables = await Promise.all(symbols.map((s) => d3.csv(`/data/${s.toLowerCase()}.csv`, d3.autoType)));
const stocks = symbols.flatMap((Symbol, i) => tables[i].map((d) => ({Symbol, ...d})));
const hover = cm.selection();

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

root
  .data(stocks)
  .transform(cm.encode, {x: "Date", y: "Close", stroke: "Symbol"})
  .transform(cm.plane, {y: {grid: true}, stroke: {legend: true}})
  .add(cm.lineY)
  .add(cm.circle, {filter: hover, r: 3.5, fill: "stroke", stroke: "white"})
  .add(cm.nearestX, {as: hover, shared: "x"})
  .add(cm.tip, {filter: hover, shared: true, rule: true, format: {Close: (d) => d.toFixed(2)}});

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

A selection read in .data filters rows. Brush a histogram to filter the other two:

js
const days = await d3.csv("/data/seattle-weather.csv", d3.autoType);
const brush = cm.selection({resolve: "intersect"});

function histogram(field) {
  const renderer = cm.svg({width: 640, height: 160});
  const root = cm.flow({transition: {duration: 250}}).renderer(renderer);
  root
    .data(() => [
      ...days.map((d) => ({...d, layer: "all"})),
      ...days
        .filter((d) => brush.test({datum: d}, {except: field, empty: true}))
        .map((d) => ({...d, layer: "selected"})),
    ])
    .transform(cm.encode, {x: field, fill: "layer"})
    .transform(cm.binX, {y: "count", thresholds: 20})
    .transform(cm.plane, {y: {grid: true}, fill: {domain: ["all", "selected"], range: ["#ddd", "steelblue"]}})
    .add(cm.rect, cm.insetX(0.5))
    .add(cm.brushX, {as: brush, source: field});
  root.render();
  return renderer.node();
}

document.body.append(...["precipitation", "temp_max", "wind"].map(histogram));

In Vega-Lite, the brush is a parameter, and a second layer filters by it:

json
{
  "repeat": {"column": ["distance", "delay", "time"]},
  "spec": {
    "layer": [
      {"params": [{"name": "brush", "select": {"type": "interval", "encodings": ["x"]}}],
       "mark": "bar", "encoding": {"x": {"field": {"repeat": "column"}, "bin": {"maxbins": 20}}, "y": {"aggregate": "count"}, "color": {"value": "#ddd"}}},
      {"transform": [{"filter": {"param": "brush"}}],
       "mark": "bar", "encoding": {"x": {"field": {"repeat": "column"}, "bin": {"maxbins": 20}}, "y": {"aggregate": "count"}}}
    ]
  }
}

Selections and their predicates come from Vega-Lite, and clauses resolved by intersection resemble Mosaic's Selection. The difference is that the predicate is ordinary code inside the flow, so it can drive anything a flow computes: which rows, which bins, which charts. And because rendering diffs scenes, the bars grow and shrink to their new counts with no extra code.

More: brushable scatterplot matrix, focus + context, legend filter.

One flow, three renderers ​

The flow doesn't know how it's drawn. The sunflower of §2 and the column chart of §3, on a canvas, only swap the renderer:

js
const seafood = await d3.csv("/data/seafood.csv", d3.autoType);
const golden = Math.PI * (3 - Math.sqrt(5));

const sunflower = cm.canvas({width: 320, height: 320});
cm.flow()
  .renderer(sunflower)
  .data(d3.range(600))
  .transform(cm.bind, {
    x: (i) => Math.sqrt(i) * Math.cos(i * golden),
    y: (i) => Math.sqrt(i) * Math.sin(i * golden),
    r: (i) => i,
    fill: (i) => i,
  })
  .transform(cm.fit, {margin: 10})
  .transform(cm.scale, {r: {range: [1, 5]}, fill: {scale: d3.scaleSequential(d3.interpolateYlOrBr)}})
  .append(cm.circle)
  .render();

const columns = cm.canvas({width: 320, height: 320});
cm.flow()
  .renderer(columns)
  .data(seafood)
  .transform(cm.encode, {x: "lake", y: "count"})
  .transform(cm.groupX, {y: "sum"})
  .transform(cm.spreadX)
  .transform(cm.plane)
  .add(cm.rect, {fill: "steelblue"})
  .render();

document.body.append(sunflower.node(), columns.node());

The renderers:

Charming began as a creative-coding library, and its terminal renderer comes from Charming.py, for ASCII art.

Small, and fast enough ​

Lines of source code, excluding tests, comments and generated files:

LibraryLines of code
Charming: core, vis and the three renderers~9.4k
Observable Plot~13.0k
Vega-Lite + Vega~25.1k + ~27.8k

The scopes differ, and the comparison is rough:

  • Plot has many more marks and transforms.
  • Vega includes an expression language, an incremental dataflow runtime and geography.
  • Charming's vis layer is about 5.2k lines.

The point is that composition, animation and interaction don't need a lot of separate code once they share one model.

The cost of re-running a flow stays interactive. Below are the median milliseconds per update in Chrome, for the same charts in both libraries; lower is better:

BenchmarkCharmingVega-Lite
Scatterplot matrix, brushing4.44.1
Multiple lines, hovering2.86.8
Stacked columns, legend clicks0.50.3
Crossfilter, brushing2.70.6
Crossfilter on 10× the data18.71.9

Charming redraws only the shapes that changed, but it re-runs every step that read the selection. Vega's dataflow updates only the changed tuples, which wins on larger data (§10).

Limits and open questions ​

Limits:

  • Large data: Charming re-runs the steps of a flow, not individual tuples. Vega's incremental dataflow is about 10× faster on the crossfilter with 10× the data. Large data probably belongs in a query engine like Mosaic, rather than in incremental transforms.
  • Portability: a flow is a JavaScript program, not a JSON spec. It can't be generated, stored or edited by tools the way Vega-Lite specs are.
  • Accessibility: not addressed yet. Nested flows are a structure that screen-reader navigation could follow, as in Olli, but we haven't tried it.
  • Coverage: fewer marks and transforms than Plot; no geography yet.

Open questions:

  • Compiling: because the tree is lazy, the whole program is known before it runs. Can the data steps compile to a query engine such as Mosaic and DuckDB, and the shape steps to the GPU?
  • Animation: what is a good grammar of animation when animation is a scene diff, so that timing can be designed rather than defaulted?
  • Evaluation: how do these trade-offs compare for authors? This is open; the examples here reproduce charts from Vega-Lite, Plot, D3 and GoFish, but that shows expressiveness, not usability.

Charming is by Bairui Su. Browse the examples or get started.