Skip to content

Focus + Context ​

Apple's closing price, with a small overview below. Brushing the dates of the overview zooms the chart above it to them: the data of the focus reads the brush's selection, so it's computed again as the brush moves, and its x domain follows; without a brush, it shows every date. Its y domain is that of every date, as the overview's, so that the prices compare. Drag across the overview to zoom.

js
const aapl = await d3.csv("/data/aapl.csv", d3.autoType);
const brush = cm.selection();

const focus = cm.svg({width: 640, height: 320});
const focusRoot = cm.flow().renderer(focus);

focusRoot
  .data(() => aapl.filter((d) => brush.test({datum: d}, {empty: true})))
  .transform(cm.encode, {x: "Date", y: "Close"})
  .transform(cm.plane, {y: {grid: true, domain: d3.extent(aapl, (d) => d.Close)}})
  .add(cm.lineY, {stroke: "steelblue"});

focusRoot.render();

const context = cm.svg({width: 640, height: 100});
const contextRoot = cm.flow().renderer(context);

contextRoot
  .data(aapl)
  .transform(cm.encode, {x: "Date", y: "Close", y1: () => 0})
  .transform(cm.plane, {y: {axis: null}})
  .add(cm.areaY, {fill: "steelblue", fillOpacity: 0.2})
  .add(cm.brushX, {as: brush});

contextRoot.render();
document.body.append(focus.node(), context.node());