如何在R中找到一个图中多条直线的交点?

nmpmafwu  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(97)

示例代码:

m=matrix(1:54,nrow=9)
l=1:6
plot(l,m[1,],type="l",xlim=1:6)
lines(l,m[2,])
lines(l,m[3,])
legend(2,3,legend=c("m1","m2","m3")))

现在,我如何找到m1m2相交的点?任何帮助都是感激的。

vxf3dgd4

vxf3dgd41#

  • 注意,这是对OP的original question的回答;此后,他们对自己的问题进行了大幅修改。

这是@dcarlson的解决方案here的扩展,添加lm()来从点的向量中找到截距和斜率。

intersection <- function(x, y1, y2) {
  l1 <- unname(coef(lm(y1 ~ x)))
  l2 <- unname(coef(lm(y2 ~ x)))
  x_int <- (l2[1] - l1[1]) / (l1[2] - l2[2])
  y_int <- l1[1] + l1[2] * x_int
  c(x = x_int, y = y_int)
}

# intersection of m2 and m5
m2_m5 <- intersection(l, m[2, ], m[5, ])
m2_m5
#        x         y 
# 0.720027 56.960115 

# intersection of m3 and m5
m3_m5 <- intersection(l, m[3, ], m[5, ])
m3_m5
#         x         y 
# -25.59092 -21.97391

m3和m5的交点不在你的绘图区域内,但我们可以绘制m2和m5的交点:

plot(l, m[2, ], type = "l", lwd = 2, col = 2, ylim = c(50, 90))
lines(l, m[3, ], type = "l", lwd = 2, col = 3)
lines(l, m[5, ], type = "l", lwd = 2, col = 5)
legend("topleft", legend = c("m2", "m3", "m5"), col = c(2, 3, 5), lty = 1, lwd = 2)
points(m2_m5[[1]], m2_m5[[2]], cex = 2, col = 2, lwd = 2)

相关问题