在散点图中识别重叠点

3

有没有一种简单的方法来识别包含在红色和蓝色多边形(即绿色多边形)交集内部的d1d2点。

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个回答

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")

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接