【发布时间】:2017-11-09 13:51:26
【问题描述】:
我想在给定地图中划定 Voronoi 图。我受到以下问题的启发来执行此任务:
Voronoi diagram polygons enclosed in geographic borders
Combine Voronoi polygons and maps
但有些事情(可能很明显)让我无法理解:我得到了与我预期相反的结果。我要的是按图切图,而不是按图切图。
这是我的代码:
library(rgdal) ; library(rgeos) ; library(sp)
library(tmap) ; library(raster) ; library(deldir)
MyDirectory <- "" # the directory that contains the sph files
### Data ###
stores <- c("Paris", "Lille", "Marseille", "Nice", "Nantes", "Lyon", "Strasbourg")
lat <- c(48.85,50.62,43.29,43.71,47.21,45.76,48.57)
lon <- c(2.35,3.05,5.36,7.26,-1.55,4.83,7.75)
DataStores <- data.frame(stores, lon, lat)
coordinates(DataStores) <- c("lon", "lat")
proj4string(DataStores) <- CRS("+proj=longlat")
### Map ###
# link : http://www.infosig.net/telechargements/IGN_GEOFLA/GEOFLA-Dept-FR-Corse-TAB-L93.zip
CountiesFrance <- readOGR(dsn = MyDirectory, layer = "LIMITE_DEPARTEMENT")
BordersFrance <- CountiesFrance[CountiesFrance$NATURE %in% c("Fronti\xe8re internationale","Limite c\xf4ti\xe8re"), ]
proj4string(BordersFrance) <- proj4string(DataStores)
BordersFrance <- spTransform(BordersFrance, proj4string(DataStores))
### Voronoi Diagramm ###
ResultsVoronoi <- PolygonesVoronoi(DataStores)
### Voronoi diagramm enclosed in geographic borders ###
proj4string(ResultsVoronoi) <- proj4string(DataStores)
ResultsVoronoi <- spTransform(ResultsVoronoi, proj4string(DataStores))
ResultsEnclosed <- gIntersection(ResultsVoronoi, BordersFrance, byid = TRUE)
plot(ResultsEnclosed)
points(x = DataStores$lon, y = DataStores$lat, pch = 20, col = "red", cex = 2)
lines(ResultsVoronoi)
这里是PolygonesVoronoi 函数(感谢其他帖子和Carson Farmer blog):
PolygonesVoronoi <- function(layer) {
require(deldir)
crds = layer@coords
z = deldir(crds[,1], crds[,2])
w = tile.list(z)
polys = vector(mode='list', length=length(w))
require(sp)
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'))))
}
【问题讨论】:
-
您是否注意到您链接的两个问题的答案都使用了修改后的 voronoi 函数来限制给定多边形的范围?尝试用修改后的
voronoipolygons函数之一替换您的PolygonesVoronoi(请注意,您需要将地图作为多边形)。