首页 > 解决方案 > 使用 geom_sf 绘制基于点的内核映射

问题描述

有没有人知道如何根据事件的发生来绘制内核密度ggplot2sf

例如,考虑包中的meuse数据集sp(假设每个点都是一个事件发生)

library(sf)
library(ggplot2)

# data
data(meuse, package = "sp")

# as_sf
meuse_sf <- st_as_sf(meuse, coords = c("x", "y"), crs = 28992)

# example
ggplot(data = meuse_sf) +
  geom_sf(alpha = .3) +
  theme_bw()

事件发生。

我想使用 geom_sf 创建一个二维内核密度。

Ps:使用起来很容易stat_density_2d,但是我正在处理空间数据并且它有一个多边形边框。

标签: rggplot2geospatialsf

解决方案


在此处输入图像描述请让我知道这种方法是否有效。我能够通过从 sf 对象的几何列中提取坐标来创建密度表面。purrr 函数 map_dbl 通过将某个函数应用于列表的每个元素来返回一个数字向量。在这种情况下,每个点要素的几何由长度为 2 的数值向量表示,因此我们将每个几何的第一个元素作为 x 坐标向量,然后将第二个元素作为 y 坐标向量。

library(sf)
library(ggplot2)

data(meuse, package = "sp")

meuse_sf <- st_as_sf(meuse, coords = c("x", "y"), crs = 28992)

ggplot(data = meuse_sf) +
  geom_sf() +
  theme_bw() +
  stat_density_2d(mapping = ggplot2::aes(x = purrr::map_dbl(geometry, ~.[1]),
                                         y = purrr::map_dbl(geometry, ~.[2]),
                                         fill = stat(density)),
                  geom = 'tile',
                  contour = FALSE,
                  alpha = 0.5)

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.0.0 sf_0.7-0     

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.19     rstudioapi_0.8   bindr_0.1.1      magrittr_1.5     MASS_7.3-50      units_0.6-1     
 [7] tidyselect_0.2.4 munsell_0.5.0    colorspace_1.3-2 R6_2.2.2         rlang_0.2.2      plyr_1.8.4      
[13] dplyr_0.7.6      tools_3.5.1      grid_3.5.1       gtable_0.2.0     e1071_1.7-0      DBI_1.0.0.9000  
[19] withr_2.1.2      class_7.3-14     digest_0.6.17    yaml_2.2.0       lazyeval_0.2.1   assertthat_0.2.0
[25] tibble_1.4.2     crayon_1.3.4     bindrcpp_0.2.2   spData_0.2.9.4   purrr_0.2.5      glue_1.3.0      
[31] labeling_0.3     compiler_3.5.1   pillar_1.3.0     scales_1.0.0     classInt_0.2-3   pkgconfig_2.0.2

推荐阅读