我有多套积分(不同年份~20岁)
我想使用r空间包为每组点生成thiessen多边形。
我知道这可以使用GIS来完成,但因为我想要一个批处理过程中的某些内容将是
有帮助的。
答案 0 :(得分:17)
您还没有让我们访问您的数据,但这里是一个代表世界城市的点的示例,使用了Carson Farmer在his blog上描述的方法。希望它能让你开始......
# Carson's Voronoi polygons function
voronoipolygons <- function(x) {
require(deldir)
require(sp)
if (.hasSlot(x, 'coords')) {
crds <- x@coords
} else crds <- x
z <- deldir(crds[,1], crds[,2])
w <- tile.list(z)
polys <- vector(mode='list', length=length(w))
for (i in seq(along=polys)) {
pcrds <- cbind(w[[i]]$x, w[[i]]$y)
pcrds <- rbind(pcrds, pcrds[1,])
polys[[i]] <- Polygons(list(Polygon(pcrds)), ID=as.character(i))
}
SP <- SpatialPolygons(polys)
voronoi <- SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1],
y=crds[,2], row.names=sapply(slot(SP, 'polygons'),
function(x) slot(x, 'ID'))))
}
示例1:输入是SpatialPointsDataFrame:
# Read in a point shapefile to be converted to a Voronoi diagram
library(rgdal)
dsn <- system.file("vectors", package = "rgdal")[1]
cities <- readOGR(dsn=dsn, layer="cities")
v <- voronoipolygons(cities)
plot(v)
示例2:输入是x,y坐标的向量:
dat <- data.frame(x=runif(100), y=runif(100))
v2 <- voronoipolygons(dat)
plot(v2)
答案 1 :(得分:2)
与jbaums所示的原理相同,但代码更简单:
{{1}}
答案 2 :(得分:0)
请注意,Voronoi cells are also known as Thiessen polygons。
或者,可以使用Simple Features for R,特别是sf::st_voronoi()
函数。以下是受this help page启发的示例:
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
# generate some random points
set.seed(2020-05-27)
n <- 50
points <- runif(n) %>%
matrix(ncol = 2) %>%
st_multipoint()
# Voronoi tesselation
voronoi_grid <- st_voronoi(points)
plot(voronoi_grid, col = NA)
plot(points, add = TRUE, col = "blue", pch = 16)
由reprex package(v0.3.0)于2020-05-27创建
由于您提到有多组积分,一年一组,因此可以使用列表并对其进行迭代,例如:
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
# generate a list of length 20, each element containing with random points
set.seed(2020-05-27)
yrs <- 20
n <- 50
points_lst <- vector(mode = "list", length = yrs)
for (i in 1:yrs) {
points_lst[[i]] <- runif(n) %>%
matrix(ncol = 2) %>%
st_multipoint()
}
# Voronoi tesselation for each element of the list
voronoi_grids_lst <- lapply(points_lst, st_voronoi)
# plot 1st element
plot(voronoi_grids_lst[[1]], col = NA)
由reprex package(v0.3.0)于2020-05-27创建