Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend line with given points

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. enter image description here 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!

like image 397
tomtomtom Avatar asked Jan 16 '14 17:01

tomtomtom


People also ask

How do I extend a line from a point?

Select the line segment to which you want to extend a line. on the Advanced Editing toolbar. Click the endpoint of the feature you want to extend. The line you clicked is extended to the selected line.

Can you extend a line segment?

A line segment is part of a line or a ray which has two distinct unique bounding end points. It can't be extended in either direction and it is of fixed length.

How do you extend a line in 3d?

Move the cursor over the edge or line to which you want to extend the selected linework. Click when a temporary line is displayed extending along and beyond the edge/line in both directions. Click any point on the linework you want to extend or click the edge or line to which you want to extend the linework.


1 Answers

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)];
}
like image 68
meetamit Avatar answered Sep 22 '22 00:09

meetamit