Empty Pipes

Panning and Zooming with D3v4

  • 03 Jul 2016
  • |
  • javascript
  • d3
  • zooming
  • |

All that’s necessary for panning and zooming is a translation [tx, ty] and a scale factor k. When a zoom transform is applied to an element at position [x0, y0], its new position becomes [tx + k × x0, ty + k × y0]. That’s it. Everything else is just sugar and spice on top of this simple transform.

The major difference between zooming in D3v3 and and D3v4 is that the behavior (dealing with events) and the transforms (positioning elements) are more separated. In v3, they used to be part of the behavior whereas in v4, they’re part of the element on which the behavior is called.

To illustrate, let’s plot 4 points. The rest of this post will only deal with data in one dimension. It should be trivial to expand to two dimensions. The points will represent the values 1, 1010, 1020 and 5000:

    var xScale = d3.scaleLinear()

    var dataPoints = [1,1010,1020,5000];

    .attr('r', 7)
    .attr('cx', function(d) { return xScale(d); });

We can see that two of the points, 1010 and 1020, are virtually on top of each other. Using our xScale, we can determine that they’re less than 1 pixel apart.

    xScale(1010) //180.8
    xScale(1020) //181.6

What if we want to zoom in so that they’re 10 pixels apart? We’ll first need to calculate the scale factor, k:

    var k = 10 / (xScale(1020) - xScale(1010))  //~ 12.5 

Let’s say we want the point 1010 to be positioned at pixel 200. We need to determine tx such that 200 = tx + k × xScale(1010)

    var tx = 200 - k * xScale(1010) //-2600

When we apply this to our plot.

    var k = 10 / (xScale(1020) - xScale(1010))
    var tx = 200 - k * xScale(1010)
    var t = d3.zoomIdentity.translate(tx, 0).scale(k)

    .attr('r', 7)
    .attr('cx', function(d) { return t.applyX(xScale(d)); });

We get two lovely separated circles.

Fantastic, right? But notice that the top axis still refers to the old domain. This is because we never changed it. In the old version of D3, we would attach the axis to the zoom behavior, set the translate and scale properties and be done with it. In v4, we have to rescale our linear scale manually and use the rescaled version to create the axis:

    var xNewScale = t.rescaleX(xScale)

    var xTopAxis = d3.axisTop()

The examples above demonstrate how the zoom transforms work, but they don’t actually use the zoom behavior. For that we need to create a behavior and attach it to an element:

    var circles = svg.selectAll('circle');
    var zoom = d3.zoom().on('zoom', zoomed);

    function zoomed() {
        var transform = d3.event.transform;

        // rescale the x linear scale so that we can draw the top axis
        var xNewScale = transform.rescaleX(xScale);

        // draw the circles in their new positions
        circles.attr('cx', function(d) { return transform.applyX(xScale(d)); });


Here we recompute the zoom transform every time there is a zoom event and reposition each circle. We also rescale the x-scale so that we can use it to create an axis. The astute observer will note that transform.applyX(xScale(d)) is actually equivalent to xNewScale(d). Automatic rescaling was possible using v3 by calling zoom.x(xScale), but this has been done away with in favor of explicit rescaling using transform.rescaleX(xScale).

The code above works but if we had programmatically zoomed in beforehand (as we did in the previous section by applying the transform), then applying the zoom behavior would remove that transform as soon as we start zooming.


Because in the zoomed function we obtain a transform from d3.event.transform. In previous versions of D3, this would come from the zoom behavior itself (zoom.translate and zoom.scale). In v4, it comes from the element on which the zoom behavior is called (gMain). To programmatically zoom in and then apply the zoom behavior starting from there, we need to set the zoom transform of the gMain element before we call the behavior:

var k = 10 / (xScale(1020) - xScale(1010))
var tx = 200 - k * xScale(1010)
var t = d3.zoomIdentity.translate(tx, 0).scale(k)

gMain.call(zoom.transform, t);

Now we start with an already zoomed in view and can zoom in and out using the mouse.

To wrap up this post, let’s combine these techniques to create a figure which automatically zooms between random data points (a la M. Bostock’s Zoom Transitions Block). How do we do this?

First, we need a function to call every time we want to jump to a point:

    let targetPoint = 1010;

    function transition(selection) {
        let n = dataPoints.length;
        let prevTargetPoint = targetPoint;

        // pick a new point to zoom to
        while (targetPoint == prevTargetPoint) {
            let i = Math.random() * n | 0
            targetPoint = dataPoints[i];

        .call(zoom.transform, transform)
        .on('end', function() { circles.call(transition); });


This function picks a random point (targetPoint) and calls a transition on the selection. In our case, the selection will be the circles. When the transition is over, we simply call the function again to start it over.

Second, we need a transform to center the view on the target point:

    function transform() {
        // put points that are 10 values apart 20 pixels apart
        var k = 20 / (xScale(10) - xScale(0))
        // center in the middle of the visible area
        var tx = (xScale.range()[1] + xScale.range()[0])/2 - k * xScale(targetPoint)
        var t = d3.zoomIdentity.translate(tx, 0).scale(k)
        return t;

And that’s all. Just remember, when zooming and panning the position of the transformed point [x1,y1] = [tx + k × x0, ty + k × y0]. Everything else is just window dressing.