示例代码:
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")))
现在,我如何找到m1和m2相交的点?任何帮助都是感激的。
m1
m2
vxf3dgd41#
这是@dcarlson的解决方案here的扩展,添加lm()来从点的向量中找到截距和斜率。
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)
1条答案
按热度按时间vxf3dgd41#
这是@dcarlson的解决方案here的扩展,添加
lm()
来从点的向量中找到截距和斜率。m3和m5的交点不在你的绘图区域内,但我们可以绘制m2和m5的交点: