Code

D3.js

Brush & Linked Views

Expert Focus + context: brush a time window in the mini overview to dynamically filter and rescale the detail chart above it. d3-brush

// Two separate x-scales:
//   xDetail — drives the zoomed view
//   xOv     — fixed to the full range

const brush = d3.brushX()
  .extent([[0, 0], [iW, overviewH]])
  .on('brush end', (event) => {
    if (!event.selection) return;

    const [x0, x1] = event.selection;

    // Convert pixel selection → dates
    const newDomain = [
      xOv.invert(x0),
      xOv.invert(x1),
    ];

    // Rescale the detail x-axis
    xDetail.domain(newDomain);

    // Redraw detail chart paths
    detailArea.attr('d', areaFn);
    detailLine.attr('d', lineFn);

    // Redraw detail x-axis ticks
    gXDetail.call(
      d3.axisBottom(xDetail).ticks(6)
    );
  });

// Attach brush to overview g
overviewG.append('g').call(brush);

// Set initial selection
brushG.call(brush.move, [0, iW / 3]);
Key APIs
  • d3.brushX() — horizontal brush; d3.brushY() / d3.brush() for other orientations
  • .extent([[x0,y0],[x1,y1]]) — constrain the brush to a region
  • event.selection[pixelStart, pixelEnd] of the current selection
  • scale.invert(pixel) — converts a pixel offset back to a domain value
  • brush.move(g, selection) — programmatically set the brush position
  • Focus+context is a classic D3 pattern: overview shows all data, detail shows a filtered window