r - 使用来自 OpenStreetMap 的数据在 R 中构建 Voronoi 图

标签 r openstreetmap r-sf voronoi

在此示例中,我尝试根据与村中两座教堂之一的接近程度为英国韦特旺村的 map 着色。这是没有 Voronoi 图的基本图的代码,它将村庄和两座教堂的多边形显示为点。

library(osmdata)
library(sf)
library(tidyverse)

bb <- getbb("Wetwang", featuretype = "settlement", format_out = "polygon")

wetwang <- getbb("Wetwang", featuretype = "settlement") %>% 
  opq() %>% 
  add_osm_feature(key = "boundary", value = "administrative") %>% 
  osmdata_sf() %>% 
  trim_osmdata(bb)

churches <- getbb("Wetwang", featuretype = "settlement") %>% 
  opq() %>% 
  add_osm_feature(key = "building", value = "church") %>% 
  osmdata_sf() %>% 
  trim_osmdata(bb)

ggplot() +
  geom_sf(data = wetwang$osm_multipolygons) +
  geom_sf(data = churches$osm_polygons %>% 
            st_centroid()) +
  theme_void()

这是输出:

enter image description here

我正在尝试使用 st_voronoi 来构建这些 Voronoi 图。但是,它似乎不起作用:

envelope <- st_cast(wetwang$osm_multipolygons, "POLYGON")

church_areas <- churches$osm_polygons %>% 
  st_centroid() %>% 
  st_union() %>% 
  st_voronoi(envelope = envelope)

这会失败,因为

Error in vapply(lst, class, rep(NA_character_, 3)) : 
  values must be length 3,
 but FUN(X[[1]]) result is length 2

如果不传递信封参数,我会得到一张 map ,其中图表并未延伸到 Wetwang 的整个区域:

church_areas <- churches$osm_polygons %>% 
  st_centroid() %>% 
  st_union() %>% 
  st_voronoi() %>% 
  st_collection_extract(., "POLYGON") %>% 
  st_as_sf()

ggplot() +
  geom_sf(data = wetwang$osm_multipolygons) +
  geom_sf(data = churches$osm_points) +
  geom_sf(data = church_areas) +
            theme_void()

enter image description here

那么我做错了什么?

最佳答案

一种可能的解决方案:

# create sf objects to use. churches$osm_points has many points for each church
#  finding the centroid of churches$osm_polygons solves this
churches_single_point <- churches$osm_polygons %>% st_centroid()
churches_polygon <- churches$osm_polygons
wetwang_sf <- wetwang$osm_multipolygons

church_voronoi <- churches_single_point %>%
  st_geometry() %>%
  st_union() %>%
  st_voronoi(envelope = st_geometry(wetwang_sf)) %>%
  st_cast() %>%
  st_as_sf()

# use st_intersection to "crop" the voronoi & join it with churches_single_point
#  plot & fill by name.y
church_voronoi %>% 
  st_intersection(wetwang_sf) %>%
  st_join(churches_single_point) %>%
  ggplot() + 
  geom_sf(aes(fill = name.y))

enter image description here

关于r - 使用来自 OpenStreetMap 的数据在 R 中构建 Voronoi 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74198735/

相关文章:

r - if else 或条件语句在警告消息后更改 for 循环函数

R将多个数据表 append 到列表

java - 使用 STAX API 进行 XML 解析

替换 sf 中列表中的几何图形

windows - R 未检测到 Rtools

r - 在 scale_fill_manual ggplot 调用中以编程方式指定颜色

javascript - OpenLayers 中的最小/最大缩放级别

javascript - OpenStreetMap leafletjs 删除树层

r - 使用 R 包 sf 编写带坐标的 CSV

r - 如何使用 R 中的 sf 包旋转网格?