Phae7rae Phae7rae - 1 year ago 66
Javascript Question

In d3, how to get the interpolated line data from a SVG line?

I display a line chart with D3 with roughly the following code (given the scale functions

and the float array

var line = d3.svg.line()
.x(function (d, i) { return x(i); })
.y(function (d) { return y(d); });'.line').attr('d', line(data));

Now I want to know the vertical height of the line at a given horizontal pixel position. The
array has lesser data points than pixels and the displayed line is interpolated, so it is not straight-forward to deduce the height of the line at a given pixel just from the

Any hints?

Answer Source

Edited 19-Sep-2012 per comments with many thanks to nrabinowitz!

You will need to do some sort of search of the data returned by getPointAtLength. (See

// Line
var line = d3.svg.line()
     .x(function (d) { return i; })
     .y(function(d, i) { return 100*Math.sin(i) + 100; });

// Append the path to the DOM"svg#chart") //or whatever your SVG container is
     .attr("d", line([0,10,20,30,40,50,60,70,80,90,100]))
     .attr("id", "myline");

// Get the coordinates
function findYatX(x, linePath) {
     function getXY(len) {
          var point = linePath.getPointAtLength(len);
          return [point.x, point.y];
     var curlen = 0;
     while (getXY(curlen)[0] < x) { curlen += 0.01; }
     return getXY(curlen);

console.log(findYatX(5, document.getElementById("myline")));

For me this returns [5.000403881072998, 140.6229248046875].

This search function, findYatX, is far from efficient (runs in O(n) time), but illustrates the point.