I have this simple code that plots two intersecting lines:
x <- c(1,2,3,4,5,6)
y2 <- c(6,5,4,3,2,1)
y1 <- c(1,2,3,4,5,6)
plot(x, y1)
plot(x, y1, type="o", col="blue", pch="o", lty=1)
points(x, y2, col="red", pch="*")
lines(x, y2, col="red", lty=1)
I then use the locator() function to manually find the position of the intersection of the two lines, using the coordinates of the intersection to plot a label at the intersection with the text() function, and draw a vertical line at the intersection position with the abline() function.
p <- locator()
text(p$x, p$y+0.4, labels="S")
abline(v=p$x, lty=3)
However, here I have run into a problem as I want thart the vertical line at the intersection position would stop at the intersection (instead of going along the entire y axis).
Can someone give me a hint on how to do this?
You can use
segments
to draw a line segment between two x, y points, so you can do:Note also that if your lines are always straight like this you can find the intersection algrebaically, which is more accurate and reproducible than using
locator()
: