All examples By author By category About

63anp3ca

Signal Plot III (zoom)

Signal Plot III

Line chart that displays three dimensions of data taken from an accelerometer. This example is designed to implement zooming, while still maintaining the highlighting and tooltips from Signal Plot II.

Zooming

The chart uses d3.zoom to implement zooming and panning for the x-axis. Adding the zoom can be done with relatively few steps:

Create the Zoom Behavior:

  // setup zoom
  var zoom = d3.zoom()
      .scaleExtent([1, 50])
      .translateExtent([[0, 0], [width, height]])
      .extent([[0, 0], [width, height]])
      .on("zoom", zoomed);

The callback function zoomed will also need to be defined. Below shows the callback for rescaling only in the x dimension, as well as redrawing the x-axis:

  function zoomed() {
    var t = d3.event.transform;
    x.domain(t.rescaleX(x0).domain());
    dims.forEach(dim => {
      var selector = ".line--" + dim;
      svg.select(selector)
        .attr("d", lines[dim]);
    });
    svg.select(".axis--x").call(d3.axisBottom(x));
  }

Note how the x0 scale is also needed for a point of reference: var x0 = d3.scaleLinear().range([0, width]); ... x0.domain(x.domain());

Create the Zoom Portal:

  // create zoom portal in background
  var rect = svg.append("rect")
      .attr("class", "zoom")
      .attr("width", width)
      .attr("height", height)
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
      .call(zoom); 

Note: Make sure that this section goes after the zoom behavior definition, but before drawing any of the lines or axes. This will position the zoom portal in the back, allowing the highlighting and tooltip events to still propagate.

Add the Clip-Path:

// Create clip-path
svg.append("defs").append("clipPath")
    .attr("id", "clip")
   .append("rect")
    .attr("width", width)
    .attr("height", height);

Styling:

Make sure that zoom portal accepts pointer-events, and that the lines use the clip-path.

.zoom {
  fill: none;
  cursor: move;
  pointer-events: all;
}

.line {
  fill: none;
  opacity: 0.9;
  stroke-width: 1.5px;
  clip-path: url(#clip);
}

Set initial zoom/position: (optional)

This little snippet sets the initial zoom to x2 and sets the position to the start of the data:

  // Set initial zoom/position
  zoom.scaleBy(rect, 2);
  zoom.translateBy(rect, width);

Note: The order matters here: scale then translate.

Highlighting:

Highlighting follows a pattern inspired by lwthatcher's block: Multi y-axis with mouseover, where when a line is moused-over the line is highlighted, while other lines are dimmed.

Tooltips:

The tooltips are implemented based off of d3noob's block: Simple tooltips in v4, with some additional css styling changes.

Built with blockbuilder.org

forked from lwthatcher's block: Signal Plot I

forked from lwthatcher's block: Signal Plot II (highlighting + tooltips)

forked from lwthatcher's block: Signal Plot III (zoom)