I am trying to add a tangent to my plot at the point x = 30
and I want to calculate the x-intersection of the tangent at y = 0.08
.
I already found a very useful example, which I tried to use, but for some reason it is not working for y = 0.08
.
I don't understand the meaning of deriv in the predict()
function nor the actual difference in between pred0 and pred1. Can someone please explain?
x <- seq(0,40)
y <- dnorm(seq(0,40), mean=25, sd=5)
plot(x, y)
spl <- smooth.spline(y ~ x)
lines(spl, col="green")
newx <- 30
pred0 <- predict(spl, x=newx, deriv=0)
pred1 <- predict(spl, x=newx, deriv=1)
yint <- pred0$y - (pred1$y*newx)
xint <- -yint/pred1$y
xint
plot(x, y)
abline(h=0, col="red")
lines(spl, col="red")
points(pred0,col="red", pch=19)
lines(x, yint + pred1$y*x)
points(xint, 0, col="red", pch=19)
It seems like you have no problem calculating the tangent line and the intersect, but rather need some help in finding the x
value for a given y
value. This method will work for any smooth curve, but mark Gregors warning. There might not be a corresponding x value, or there might be several.
x <- seq(0, 40, by=0.01)
y <- dnorm(x, mean=25, sd=5)
spl <- smooth.spline(y ~ x)
plot(spl, type="l")
yval <- 0.08
ad <- abs(yval - spl$y)
if (min(ad) > max(diff(spl$y))*10) {
warning("The supplied y value is out of bounds")
}
xval <- x[which(diff(sign(diff(ad))) > 1) + 1]
points(xval, rep(yval, length(xval)))
With that xval
you can calculate the tangent as you've already done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With