maurobio
maurobio

Reputation: 1577

R plotting a line at the intersection of two lines

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?

enter image description here

Upvotes: 0

Views: 1419

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can use segments to draw a line segment between two x, y points, so you can do:

p <- locator()
text(p$x, p$y + 0.4, labels = "S")
segments(p$x, 0, p$x, p$y, lty = 3)

enter image description here

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():

dx  <- tail(x, 1) - head(x, 1)
dy1 <- tail(y1, 1) - head(y1, 1)
dy2 <- tail(y2, 1) - head(y2, 1)
grad1 <- dy1/dx
grad2 <- dy2/dx
c1 <- y1[1] - grad1 * x[1]
c2 <- y2[1] - grad2 * x[1]
xi <- (c2 - c1)/(grad1 - grad2)
yi <- grad1 * xi + c1
segments(xi, 0, xi, yi, lty = 3)
text(xi, yi + 0.4, labels = "S")

enter image description here

Upvotes: 1

Related Questions