您可以使用mgcv 包中的in.out 函数仅选择多边形内的点。您可以使用它仅绘制伊利诺伊州边界内的点。下面的示例在以伊利诺伊州为边界的矩形内添加了一个额外点,但该点不在伊利诺伊州的边界内。
library(ggplot2)
library(mgcv)
test <- data.frame(lat=c(40, 35, 39), long=c(-89, -85, -91))
state = map_data("state")
# Limit points only to those inside Illinois
point.filter = in.out(as.matrix(state[state$region=="illinois", c("lat","long")]),
as.matrix(test))
ggplot() +
geom_polygon(data=state[state$region=="illinois", ],
aes(x=long, y=lat, group=group), fill="white", color="black") +
geom_point(data=test[point.filter, ], aes(x=long, y=lat), col="blue") +
geom_point(data=test, aes(x=long, y=lat), col="red", pch=1, size=3) +
coord_map(xlim=range(state[state$region=="illinois",]$long),
ylim=range(state[state$region=="illinois",]$lat))
您可以使用in.out 来测试一组点中的每一个是否位于多个多边形中的至少一个(例如,多个状态)内,但在这种情况下,每个多边形必须由一行@987654327 分隔@。这是一个示例,我们测试一组点是否在连续的 48 个美国之内,但使用 state 数据框,每个州都有一个单独的多边形。我为这个插图添加了美国境内没有的两点:
library(dplyr) # For bind_rows() function
# Add an NA row between each state
tmp=lapply(split(state[,c("lat","long","region")], state$region), function(x) {
bind_rows(list(x, data.frame(region=NA, lat=NA, long=NA)))
})
tmp = bind_rows(tmp)
# Points for testing
test <- data.frame(lat=c(40, 35, 39, -10, 20), long=c(-89, -85, -91, -89, 0))
point.filter = in.out(as.matrix(tmp[, c("lat","long")]),
as.matrix(test))
point.filter
[1] TRUE TRUE TRUE FALSE FALSE