2017-08-16 63 views
2

我不確定是否完全理解幫助頁面來創建voronoi多邊形。用R中的簡單功能創建voronoi多邊形R

library(sf) 

# function to get polygon from boundary box 
bbox_polygon <- function(x) { 
    bb <- sf::st_bbox(x) 

    p <- matrix(
    c(bb["xmin"], bb["ymin"], 
     bb["xmin"], bb["ymax"], 
     bb["xmax"], bb["ymax"], 
     bb["xmax"], bb["ymin"], 
     bb["xmin"], bb["ymin"]), 
    ncol = 2, byrow = T 
) 

    sf::st_polygon(list(p)) 
} 

nc <- st_centroid(st_read(system.file("shape/nc.shp", package="sf")))["BIR79"] 
box <- st_sfc(bbox_polygon(nc)) 
v <- st_voronoi(nc, box) 

plot(v) 

output

任何想法解決它?

+2

一個特徵的Voronoi多邊形沒有任何意義嗎? – loki

回答

2

sf doc pages作爲起點,使用st_voronoi()示例,st_voronoi()似乎不能與包含點的sf對象一起使用。

library(sf) 

# function to get polygon from boundary box 

bbox_polygon <- function(x) { 
    bb <- sf::st_bbox(x) 

    p <- matrix(
    c(bb["xmin"], bb["ymin"], 
     bb["xmin"], bb["ymax"], 
     bb["xmax"], bb["ymax"], 
     bb["xmax"], bb["ymin"], 
     bb["xmin"], bb["ymin"]), 
    ncol = 2, byrow = T 
) 

    sf::st_polygon(list(p)) 
} 

nc <- st_read(system.file("shape/nc.shp", package="sf"))["BIR79"] 
nc_centroids <- st_centroid(nc) 
box <- st_sfc(bbox_polygon(nc_centroids)) 

head(nc_centroids) 

每個點都有一個單獨的幾何條目。

Simple feature collection with 6 features and 1 field 
geometry type: POINT 
dimension:  XY 
bbox:   xmin: -81.49826 ymin: 36.36145 xmax: -76.0275 ymax: 36.49101 
epsg (SRID): 4267 
proj4string: +proj=longlat +datum=NAD27 +no_defs 
    BIR79      geometry 
1 1364 POINT(-81.4982613405682 36.... 
2 542 POINT(-81.125145134236 36.4... 
3 3616 POINT(-80.6857465738484 36.... 
4 830 POINT(-76.0275025784544 36.... 
5 1606 POINT(-77.4105635619488 36.... 
6 1838 POINT(-76.9947769754215 36.... 

這個結合點到多點的幾何形狀:

head(st_union(nc_centroids)) 

輸出:

Geometry set for 1 feature 
geometry type: MULTIPOINT 
dimension:  XY 
bbox:   xmin: -84.05976 ymin: 34.07663 xmax: -75.80982 ymax: 36.49101 
epsg (SRID): 4267 
proj4string: +proj=longlat +datum=NAD27 +no_defs 
MULTIPOINT(-84.0597597853139 35.131067104959, -... 

使用點,而不是原來sf對象的工會工作:

v <- st_voronoi(st_union(nc_centroids), box) 
plot(v, col = 0) 

enter image description here

這裏是如何獲得正確的狀態邊界,而不是原始的邊界框。

plot(st_intersection(st_cast(v), st_union(nc)), col = 0) # clip to smaller box 
plot(nc_centroids, add = TRUE) 

enter image description here

我試圖做標記點類似的事情,我需要保持點的屬性爲生成的瓷磚。還沒有想出來。

+0

您是否設法保留屬性?我有同樣的問題。 – CPhil

+1

我必須使用'st_join'完成另一個空間連接,使用Voronoi圖塊和原始點數據,請參閱第28行https://github.com/andybega/r-misc/blob/master/spatial/marked-點到polygons.R;這顯示了結果是什麼樣子https://github.com/andybega/r-misc/blob/master/spatial/marked-points-to-polygons.md – andybega