Home > Net >  How to find y-axis values given x-axis for multiple graphs
How to find y-axis values given x-axis for multiple graphs

Time:12-08

I have a simple question that I don't know the answer to.

Assume having multiple graphs on a plot. I would like to see the exact y-values on all graphs given a specific x.

Here is a sample R code:

x1=c(1,5,7,9,15)  
y1=c(50,30,43,33,12)
x2=c(1,3,5.5,6,15)
y2=c(20,55,44,38,10)
plot(x1,y1,type="o",ylim=c(1,60))
points(x2,y2,type="o")
abline(v=c(2.5,4,6,10))

My question is how I can find the exact y-value for any vertical line crossing the plots?

enter image description here

CodePudding user response:

You can create functions that will tell you the values with approxfun.

NewPoints = c(2.5,4,6,10)
f1= approxfun(x1,y1)
f2= approxfun(x2,y2)

Now the values that you want are: f1(NewPoints) and f2(NewPoints). You can see this by plotting:

points(NewPoints, f1(NewPoints), pch=16, col="red")
points(NewPoints, f2(NewPoints), pch=16, col="blue")

Plot with additional points colored

CodePudding user response:

Use approxfun

x1=c(1,5,7,9,15)  
y1=c(50,30,43,33,12)
x2=c(1,3,5.5,6,15)
y2=c(20,55,44,38,10)
plot(x1,y1,type="o",ylim=c(1,60))
points(x2,y2,type="o")
abline(v=c(2.5,4,6,10))


# Answer
f1<- approxfun(x1,y1)
f2<-approxfun(x2,y2)

# Proof
points(x=c(2.5,4,6,10),
       y=f1(c(2.5,4,6,10)),
       col='red')


points(x=c(2.5,4,6,10),
       y=f2(c(2.5,4,6,10)),
       col='blue')

enter image description here

For the actual values

f1(c(2.5,4,6,10))
[1] 42.5 35.0 36.5 29.5

 f2(c(2.5,4,6,10))
[1] 46.25000 50.60000 38.00000 25.55556
  • Related