Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active July 18, 2022 15:56
Show Gist options
  • Save mbostock/1643051 to your computer and use it in GitHub Desktop.
Save mbostock/1643051 to your computer and use it in GitHub Desktop.
Line Transition (Broken)
license: gpl-3.0

This example is the first of three in the Path Transitions tutorial.

When you interpolate a path element’s “d” attribute using transition.attr, the default interpolator is typically d3.interpolateString. This interpolator is not specialized for SVG paths, and instead simply looks for numbers embedded in strings. Numbers in the start and end strings are paired and then interpolated. So, the default behavior when interpolating two paths pairs numbers like this:

M x0, y0 L x1, y1 L x2, y2 L x3, y3
   ↓   ↓    ↓   ↓    ↓   ↓    ↓   ↓
M x0, y1 L x1, y2 L x2, y3 L x3, y4

The first point ⟨x0,y0⟩ is interpolated to ⟨x0,y1⟩. Since the x-values are the same for each pair of points, only the y-values change, and the path doesn’t slide left as intended.

For the correct behavior, see the next example.

<!DOCTYPE html>
<meta charset="utf-8">
.line {
fill: none;
stroke: #000;
stroke-width: 1.5px;
<svg width="960" height="500"></svg>
<script src="//"></script>
var n = 40,
random = d3.randomNormal(0, .2),
data = d3.range(n).map(random);
var svg ="svg"),
margin = {top: 20, right: 20, bottom: 20, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + + ")");
var x = d3.scaleLinear()
.domain([0, n - 1])
.range([0, width]);
var y = d3.scaleLinear()
.domain([-1, 1])
.range([height, 0]);
var line = d3.line()
.x(function(d, i) { return x(i); })
.y(function(d, i) { return y(d); });
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + y(0) + ")")
.attr("class", "axis axis--y")
.attr("class", "line")
.attr("d", line)
.on("start", tick);
function tick() {
// Push a new data point onto the back.
// Pop the old data point off the front.
// Redraw the line (with the wrong interpolation).
.attr("d", line)
.on("start", tick);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment