Define overlapping points in a scatter plot

Is there an easy way to identify the points d1

as well d2

which are contained within the intersection of red as well as blue polygons (i.e. green polygon).

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

+3


source to share


2 answers


The sp package has a function point.in.polygon

that does the trick



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

      

+4


source


Based on 李哲源 Zheyuan Li's comment:

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

+3


source







All Articles