xyzzyrz
xyzzyrz

Reputation: 16416

Interpolate y-value of a d3.svg.line at a given x-value

If I have a line (possibly with some spline interpolation specified), can I extract the interpolated y-value at a given x-value? Thanks!

Upvotes: 2

Views: 996

Answers (1)

mbostock
mbostock

Reputation: 51829

It's possible, but there's not yet a built-in facility for doing so. All of D3’s splines are implemented as piecewise quadratic or cubic Bézier curves (because they are rendered to SVG path elements). You can use de Casteljau's algorithm for computing the xy-coordinates for a given parameter t in [0,1].

It's a bit harder to compute y for a given x because it's possible to have multiple y values for the same x, depending on the curve. For that, I recommend looking at this Bézier curves primer which describes an algorithm for computing a curve-line intersection; this could be simplified for a vertical line (constant x).

Upvotes: 1

Related Questions