Finding y value for an interpolated line

2,622 views
Skip to first unread message

Chung Wu

unread,
Jul 18, 2011, 6:15:13 PM7/18/11
to d3...@googlegroups.com
Hi all,

New to d3 with a beginner question :-)  I'm drawing a line chart using an interpolated line, as shown in nearly every tutorial:

var points = [{x:0,y:0.01},{x:1,y:0.05}, ...];
var y = d3.scale.linear().domain([0, 0.8]).range([0+bottomMargin, height]);
var x = d3.scale.linear().domain([0, 6.3]).range([0+leftMargin, width]);
var line = d3.svg.line()
  .x(function(p){return x(p.x);})
  .y(function(p){return -y(p.y);})
  .interpolate("basis");
g.append("svg:path").attr("d", line(points));

I'd like to draw a vertical line through it where x=4.3:

g.append("svg:line")
  .classed("threshold", true)
  .attr("x1", x(4.3)).attr("y1", 0)
  .attr("x2", x(4.3)).attr("y2", -y(1));

Now, I want to color the area under the curve to the right of the line.  I do not have a data point at x=4.3, so I have no idea what the corresponding y value is from the interpolation.

What's the easiest way to define the area under the curve here?

Thanks!

Chung

Mike Bostock

unread,
Jul 18, 2011, 6:24:26 PM7/18/11
to d3...@googlegroups.com
Hi Chung,

The interpolated value is not exposed, or even calculated directly—D3
generates cubic Bézier segments and then passes it along to the SVG
renderer. So, you could compute it if you had to, but you'd need to
evaluate a cubic Bézier.

Fortunately there's an easy solution in this case, which is to use
clipping. Use an svg:defs element to define your area, then define a
clip path for the area. Then, render the area with an svg:use element,
and clip the line using the previously-defined clip path. Here's an
earlier example that uses clipping:

http://bl.ocks.org/1067636

Mike

Chung Wu

unread,
Jul 18, 2011, 6:59:10 PM7/18/11
to d3...@googlegroups.com
Great idea; thanks!

Gianni Chiappetta

unread,
Jun 29, 2012, 2:22:54 PM6/29/12
to d3...@googlegroups.com
My apologies for resurrecting this thread. Is there an easy solution for drawing points on an interpolated line? Thanks!

Gianni

Mike Bostock

unread,
Jun 29, 2012, 2:31:39 PM6/29/12
to d3...@googlegroups.com
> Is there an easy solution for drawing points on an interpolated line?

You might find this demonstration of point-along-path interpolation relevant:

http://bl.ocks.org/1705868

Mike

Doug Manuel

unread,
Sep 11, 2016, 10:32:24 PM9/11/16
to d3-js
Reply all
Reply to author
Forward
0 new messages