9

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.

Ville
  • 547
  • 1
  • 3
  • 21
  • 2
    Doesn't the x-axis value ordering seem a bit odd? Looks like your X1 values never go below x=2 so there's no value at 0.4 really. Maybe you can clean up with example a bit to make it a bit more clear what you're rally trying to do. – MrFlick Mar 27 '18 at 19:53
  • 2
    Please edit your code. `plot(X1, Y)+lines(X1,Y) + abline(v=0.4, col="red")` does not make sense. – Henrik Mar 27 '18 at 19:55
  • 1
    My idea would be to find for `Xi`, `ai; bi` s.t. `ai <= 0.4 <= bi`, then compute the intersection between the line `y = 0.4` and the line generated by the segment `[ai, bi]`. However, as indicated above, something is odd about `X1`. – niko Mar 27 '18 at 19:58
  • 1
    Please google "intersection between lines R" and show us your attempts. Cheers – Henrik Mar 27 '18 at 19:59
  • @MrFlick I'm trying to find the Y values where `X1=0.4` and `X2=0.4` so the Y value for X1=0.4 should be approximately 2.4 and for X2=0.4 the Y value should be approximately 1.6 – Ville Mar 27 '18 at 20:00

2 Answers2

5

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

G5W
  • 36,531
  • 10
  • 47
  • 80
3

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!

bala83
  • 443
  • 4
  • 7