Ville
Ville

Reputation: 547

R: Finding the intersect of two lines

I have this simple code that creates 3 matrices and plots them:

Y=matrix(c(1,2,3,4), nrow=1)
X1=matrix(c(2,3,3.5,4.5))
X2=matrix(c(0.1, 0.2, 0.6, 1.1), nrow=1)
#Plotting
plot(X1, Y)+lines(X1,Y)
par(new=TRUE)
plot(X2, Y)+lines(X2,Y) + abline(v=0.4, col="red")

And here is the plot: enter image description here

Now, I want for the X value 0.4 to get all the Y values. The Y values are the values where the red line crosses the other two lines. So there should be two values, one value Y1 for one line and the other Y2 value for the other line.

Is there maybe any function that I could use to do this? I would really appreciate any suggestion how to do this.

Upvotes: 9

Views: 14264

Answers (2)

bala83
bala83

Reputation: 443

identify() can be used to locate points in a scatter plot by clicking with the mouse in the plot area. Hope this is what you're looking for. Check it out!

Upvotes: 3

G5W
G5W

Reputation: 37641

Because the two graphs use different x scales, this is a rather odd question. Getting the crossing point for the X2 line is easy, but the X1 line is a little more complicated.

## X2 line
AF2 = approxfun(X2, Y)
AF2(0.4)
[1] 2.5

The problem with the X1 line is that 0.4 on your graph means only X2=0.4, but X1 != 0.4. You can see that the 0.4 mark is half way between X1 = 2.5 and X1= 3, so we need to compute that value using X1 = 2.75.

AF1 = approxfun(X1, Y)
AF1(2.75)
[1] 1.75

Confirm with graph:

#Plotting
plot(X1, Y)+lines(X1,Y) + abline(v=0.4, col="red")
par(new=TRUE)
plot(X2, Y)+lines(X2,Y) 
abline(v=0.4)
points(c(0.4,0.4), c(1.75, 2.5), pch=20, col="red")

Crazy Graph

Upvotes: 5

Related Questions