Reputation: 771
I am faced with the problem of trying to interpolate values between points on a series plot i.e. my data looks like the following (please assume random x,y coordinates)
[[x0,y0], [1,1] ,[2,2], [2,3],.....[x,y]]
and from the interpolator, I would like to give it 1.5 and the interpolator function should return 1.5 for this case. In other cases where data is random, it should find a best fit for the given set of points and return the y value for the given x value
Is this possible using d3 interpolate*** functions?
Thanks
Upvotes: 0
Views: 3133
Reputation: 27534
Although you could do this with d3 interpolators, it would probably be easier to use a muli-part linear scale.
Usually, linear scales have a two-value domain and a two-value range, and all other values are calculated from the straight line between the start and end points of domain and range. However, you can set both domain and range to an array of many values (so long as both arrays are the same length), and the scale will act as a series of straight-line relationships for each section of the domain.
In other words, if you use your array of x-values as the scale's domain, and your array of y-values as the range, then you can input any x value and the scale will return the linear interpolation between adjacent y values. For values outside your points, it will extrapolate the initial or final linear relationship:
var points = [
[0,10],
[1,32],
[2,14],
[3,15]
];
var multiLine = d3.scale.linear()
.domain(
points.map(function(p){return p[0];})
)
.range (
points.map(function(p){return p[1];})
);
document.body.innerHTML =
"Line at 0.0: " + multiLine(0) + "<br/>" +
"Line at 1.0: " + multiLine(1) + "<br/>" +
"Line at 1.5: " + multiLine(1.5) + "<br/>" +
"Line at 2.3: " + multiLine(2.3) + "<br/>" +
"Line at 3.0: " + multiLine(3) + "<br/>" +
"Line at 4.0: " + multiLine(4) ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Note that you'll need to make sure that your points are sorted by x-value in order for this to work as expected.
Upvotes: 2