簡體   English   中英

R 在兩條線的交點處繪制一條線

[英]R plotting a line at the intersection of two 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使用 abline() function。

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

但是,在這里我遇到了一個問題,因為我想在交叉點 position 處的垂直線會在交叉點停止(而不是沿着整個 y 軸)。

有人可以給我一個關於如何做到這一點的提示嗎?

在此處輸入圖像描述

您可以使用segments在兩個 x、y 點之間繪制一條線段,因此您可以:

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

在此處輸入圖像描述

還要注意,如果你的線總是像這樣筆直,你可以找到交點,這比使用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")

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM