Reputation:
Sample code:
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")))
Now, how can I find the point where say m1
and m2
intersects?
Any help is appreciated.
Upvotes: -1
Views: 221
Reputation: 17204
Note, this is an answer to OP’s original question; they have since substantially edited their question.
This is an extension of @dcarlson's solution here, adding lm()
to find intercepts and slopes from vectors of points.
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
The intersection of m3 and m5 is off your plot area, but we can plot the intersection of m2 and 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)
Upvotes: 1