识别散点图中的重叠点

时间:2017-04-06 18:15:12

标签: r

是否有一种简单的方法可以识别包含在红色和蓝色多边形(即绿色多边形)交叉点内的d1以及d2的点。 / p>

graphics.off()
set.seed(42)

#DATA
d1 = data.frame(x = rnorm(20,6,2), y = rnorm(20,5,1))
d2 = data.frame(x = rnorm(20,8.5,1), y = rnorm(20,6,1.5))
ind1 = chull(d1)
ind2 = chull(d2)
p1 = data.frame(PID = rep(1, length(ind1)), POS = seq_along(ind1), X = d1$x[ind1], Y = d1$y[ind1])
p2 = data.frame(PID = rep(1, length(ind2)), POS = seq_along(ind2), X = d2$x[ind2], Y = d2$y[ind2])
#library(PBSmapping)
#p3 = joinPolys(p1, p2)
p3 = structure(list(PID = c(1L, 1L, 1L, 1L, 1L), POS = 1:5, X = c(9.19051041605104, 
9.69947043508479, 6.94793595066407, 5.50690991684707, 8.73369696007428
), Y = c(4.69045214195459, 5.98112560649435, 6.85111759082941, 
4.67133555388548, 4.3553412183288)), .Names = c("PID", "POS", 
"X", "Y"), row.names = 0:4, class = c("PolySet", "data.frame"))

#PLOT
plot(x = c(d1$x,d2$x), y = c(d1$y, d2$y), type = "n", asp = 1)
points(d1$x, d1$y, pch = 19, col = "red")
points(d2$x, d2$y, pch = 19, col = "blue")
polygon(p1$X, p1$Y, border = "red")
polygon(p2$X, p2$Y, border = "blue")
polygon(p3$X, p3$Y, border = "green", lwd = 2)

enter image description here

2 个答案:

答案 0 :(得分:4)

sp包有一个函数point.in.polygon可以实现这个技巧

library(sp)
In1 = which(point.in.polygon(d1$x, d1$y, p3$X, p3$Y) != 0)
points(d1$x[In1], d1$y[In1], pch = 19, col = "orange")
In2 = which(point.in.polygon(d2$x, d2$y, p3$X, p3$Y) != 0)
points(d2$x[In2], d2$y[In2], pch = 19, col = "orange")

答案 1 :(得分:3)

基于李哲源哲哲李的评论:

library(mgcv)
ind1_intersect = in.out(as.matrix(p3[,-(1:2)]), as.matrix(d1))
ind2_intersect = in.out(as.matrix(p3[,-(1:2)]), as.matrix(d2))

points(d1[ind1_intersect,], col = "black", pch = 19, cex = 2)
points(d2[ind2_intersect,], col = "black", pch = 19, cex = 2)

enter image description here