Reputation: 1522
I have a few lines plotted with points in a graph that look like the one in the image posted below:
let's say for example that I have the coordinates for points A & B, which I use to set the line. What I'd like to do is have the line go all the way from x=0 to x=100, adding the two missing "x" pieces.
I'm using
d3.svg.line()
to set the .x
and .y
accessor functions, and then a path to plot the line. Is there a function to add to the line or path generator that does what I'd like to obtain?
Any hint is appreciated, thanks!
Upvotes: 6
Views: 3528
Reputation: 25187
There's no built in way to do it, but it's not too hard to calculate yourself.
Let's say you're currently drawing the line between A
and B
like this:
var A = [15, 40], // x of 15 and y of 40
B = [85, 90],
line = d3.svg.line();
path.attr('d', line([A,B]))
You need to calculate p0
and p1
at x of 0 and 100, taking into account the slope of the line and a point that the line goes through. So you need a function pointAtX()
that takes as params A
and B
and a desired x coordinate and returns the appropriate y coordinate.
function pointAtX(a, b, x) {
var slope = (b[1] - a[1]) / (b[0] - a[0])
var y = a[1] + (x - a[0]) * slope
return [x, y]
}
Then you can draw the line like this:
var A = [15, 40], // x of 15 and y of 40
B = [85, 90],
line = d3.svg.line(),
p0 = pointAtX(A, B, 0),
p1 = pointAtX(A, B, 100),
path.attr('d', line([p0,p1]))
Interestingly, the implementation of pointAtX()
can be re-written to make use of d3.scale.linear
. Not sure it's better, but kind of cool:
var interpolator = d3.scale.linear()
function pointAtX(a, b, x) {
interpolator
.domain([a[0], b[0]])
.range([a[1], b[1]]);
return [x, interpolator(x)];
}
Upvotes: 12