gpt4 book ai didi

r - 使用 geom_sf 根据点绘制内核图

转载 作者:行者123 更新时间:2023-12-03 14:03:08 24 4
gpt4 key购买 nike

有没有人知道如何使用 ggplot2 根据事件的发生绘制内核密度图?和 sf ?

例如,考虑 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()

Events occurrence.

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

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

最佳答案

enter image description here请让我知道这种方法是否有效。我能够通过从 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

关于r - 使用 geom_sf 根据点绘制内核图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com