在这个例子中,我试图根据英国Wetwang村与该村两座教堂之一的距离为 map 上色.这是没有沃罗诺伊图表的基本地块的代码,它将村庄的多边形和两座教堂显示为点.

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相关问答推荐

将模拟变量乘以多个观测结果中的模拟变量

无法在我的情节中表现出显着的差异

向gggplot 2中的数据和轴标签添加大写和星号

获取列中值更改的行号

如何使用R对每组变量进行随机化?

在某些栏和某些条件下,替换dfs列表中的NA

如何删除最后一个可操作对象

打印XTS对象

如何使用FormC使简单算术运算得到的数字是正确的?

是否可以将线性模型的p值添加到tbl_summary中

R仅当存在列时才发生变异

在shiny 表格中输入的文本在第一次后未更新

通过比较来自多个数据框的值和R中的条件来添加新列

合并多个数据帧,同时将它们的名称保留为列名?

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别

如何将一列相关性转换为R中的相关性矩阵

从多行中 Select 最小值

列间序列生成器的功能

向内存不足的数据帧添加唯一行

用逗号拆分字符串,并删除一些字符