Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 44 ยท Transitions and Interaction

Brushing, Zooming and Dragging

Add d3.drag, d3.zoom and d3.brush to charts: draggable marks, pan and zoom with transforms, rescaling axes, brushing to select data and linked views.

Three behaviors in D3 turn raw pointer events into higher-level gestures:

  • d3.drag(): move an element by dragging it.
  • d3.zoom(): pan with the mouse or one finger, zoom with the wheel or pinch.
  • d3.brush(): draw a rectangle (or a range along one axis) to select things.

You attach a behavior to a selection with selection.call(behavior). Each behavior emits events you listen to with .on("name", handler), and the handler receives the usual D3 (event, d) arguments.

Dragging elements

JavaScript
const drag = d3.drag()
  .on("start", (event, d) => { /* pointer went down */ })
  .on("drag",  (event, d) => { /* event.x, event.y, event.dx, event.dy */ })
  .on("end",   (event, d) => { /* released */ });

circles.call(drag);

event.x and event.y are in the parent's coordinate space, so they work even inside transformed groups. By default the drag position is relative to the element's datum if it has x and y fields; to make dragging start without a jump, store the position on the datum and update it in the handler.

Drag points between two zones

.raise() moves the element to the end of its parent so it is drawn on top while dragging. Clamping with Math.max/min keeps the points inside the chart.

Zooming and panning

d3.zoom() listens for wheel, double-click, drag and pinch, and keeps a transform {k, x, y} (scale factor and translation). Its zoom event carries event.transform. For simple charts apply the transform to a group:

JavaScript
const zoom = d3.zoom()
  .scaleExtent([1, 8])                       // min and max zoom
  .translateExtent([[0, 0], [width, height]]) // limit panning
  .on("zoom", event => g.attr("transform", event.transform));

svg.call(zoom);

Programmatic control: svg.call(zoom.transform, d3.zoomIdentity) resets the view, and svg.transition().duration(500).call(zoom.scaleBy, 2) animates a zoom-in. Build a transform by hand with d3.zoomIdentity.translate(tx, ty).scale(k).

Scaling a whole group also scales stroke widths and text. For charts with axes, use semantic zooming: rescale the scales instead of the group, then redraw. event.transform.rescaleX(x) returns a new scale with the zoom applied:

Zoomable scatter plot with rescaled axes

Dots keep their size while the axes change, which is what users expect from a data chart. The clip path hides dots that move outside the plot area.

Note that zoom captures the mouse wheel on the SVG, so the page cannot scroll while the pointer is over it. Many sites limit this with a modifier key via .filter(event => event.ctrlKey || event.type !== "wheel").

Brushing

d3.brush() lets users select a region. Variants: d3.brush() (rectangle), d3.brushX() and d3.brushY() (one-dimensional ranges). Give it an extent, attach it to a group, and listen to start, brush and end:

JavaScript
const brush = d3.brushX()
  .extent([[m.left, 0], [W - m.right, H - m.bottom]])
  .on("brush end", ({ selection }) => {
    if (!selection) return;                 // null when cleared
    const [x0, x1] = selection.map(x.invert);
    // filter your data to [x0, x1]
  });

svg.append("g").attr("class", "brush").call(brush);

For a 2D brush, selection is [[x0, y0], [x1, y1]]. Clear it with g.call(brush.move, null) and set it programmatically with g.call(brush.move, [100, 200]). Style the selection rectangle with CSS on .selection.

Typical uses: a small overview chart whose brush zooms a large detail chart; selecting points in a scatter plot and highlighting them in another view ("linked brushing"); filtering a time range for a dashboard.

flowchart LR
  U["User gesture"] --> B["brush: selection in pixels"]
  B --> I["scale.invert: data range"]
  I --> F["filter data"]
  F --> R["redraw detail views"]

Brushing connects a gesture to a data filter.

Common mistakes

  • Zooming a group with big strokes and fonts instead of rescaling axes, which gives blurry or giant text.
  • Forgetting touch-action: none so touch dragging scrolls the page.
  • Brushing on an element that is covered by another one: the brush adds an overlay rect, so call it before drawing marks that must stay clickable, or draw marks above with pointer-events.
  • Calling brush.move in the brush handler without guarding against a loop (programmatic moves emit events too).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does event.transform contain in a zoom handler?

    The zoom transform is {k, x, y}; apply it to a group or rescale your axes with it.
  2. 2. Which is the best way to zoom a chart that has axes?

    Rescaling the scales keeps marks and text at normal size and updates the axis ticks.
  3. 3. Which brush limits selection to a horizontal range?

    brushX selects an interval along x only; brushY along y; d3.brush a rectangle.
  4. 4. How do you bring a dragged element to the front?

    raise() re-inserts the element as the last child, so it is painted on top.

Summary

  • Behaviors are attached with selection.call(...) and report through .on(...).
  • d3.drag provides event.x and event.y; store positions on the datum.
  • d3.zoom keeps a transform; for data charts rescale the scales instead of the group.
  • d3.brush, brushX, brushY yield pixel selections you convert with scale.invert to filter data.

Next: Geographic Projections and Paths