简体   繁体   English

R 在两条线的交点处绘制一条线

[英]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. 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)

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).但是,在这里我遇到了一个问题,因为我想在交叉点 position 处的垂直线会在交叉点停止(而不是沿着整个 y 轴)。

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:您可以使用segments在两个 x、y 点之间绘制一条线段,因此您可以:

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

在此处输入图像描述

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() :还要注意,如果你的线总是像这样笔直,你可以找到交点,这比使用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