Skip to content

Lines on Canvas ​

A multi-line chart of four stocks with a shared tip, drawn on a canvas. cm.nearestX with shared: "x" selects every stock at the date nearest the pointer, a dot marks each on its line, and one tip lists them; the pointer is read over the canvas, and the chart is drawn again as the selection changes.

js
// Four CSV files merged into one table, with the symbol of each stock as its first column.
const symbols = ["AAPL", "AMZN", "GOOG", "IBM"];
const tables = await Promise.all(symbols.map((symbol) => d3.csv(`/data/${symbol.toLowerCase()}.csv`, d3.autoType)));
const data = symbols.flatMap((Symbol, i) => tables[i].map((d) => ({Symbol, ...d})));

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

root
  .data(data)
  .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", strokeWidth: 1})
  .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());