Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3js nicely transition lines with added points

Tags:

d3.js

Say I have a path I created with d3 something like:

line = d3.line()
    .curve(d3.curveLinear)
    .x(function(d) { return x(d.x);})
    .y(function(d) { return y(d.y); });

data = [{x: 0, y: 0}, {x: 5, y: 5}, {x:10, y:10}];

myLine = svg.append("path")
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .datum(data)
        .attr("d", line);

This makes a nice diagonal line from 0 to 10. Now if I update my data to make some changes and add some points:

data = [{x: 1, y: 1}, {x:2, y:3}, {x: 6, y: 7}, {x:9, y:9}];

And update my line

myLine.datum(data).transition().duration(1000).attr("d", line);

It gives a weird transition where it slides the existing path to fit the first three points of the new path and awkwardly adds the final point to the end.

Similarly, if I update it to have fewer points, it shortens the line and then slides the remainder over, instead of just reshaping the line where it is.

I understand why this happens, but I'm wondering if there's a way to create a more smooth transition.

like image 327
yammerade Avatar asked Feb 22 '17 21:02

yammerade


1 Answers

You should have a look at this page and this github

.attrTween('d', function () { 
    return d3.interpolatePath(line(data), line(data2)); 
});

Have a look at this fiddle

like image 197
Tim B Avatar answered Nov 09 '22 18:11

Tim B