use*_*627 3 r tidy ggplot2 fortify terra
我想将SpatVector对象转换为数据框以在 ggplot2 中使用。
pkgs <- c("geodata", "raster", "ggplot2", "tidy")
lapply(pkgs, require, character.only = TRUE)
boundary_GB <- geodata::gadm(country = "GB", path = tempdir(), resolution = 2, level = 1)
Run Code Online (Sandbox Code Playgroud)
我目前的方法需要很长时间:
boundary_GB_df <- broom::tidy(methods::as(boundary_GB, "Spatial"))
Run Code Online (Sandbox Code Playgroud)
剧情:
ggplot(data = boundary_GB_df, mapping = aes(x = long, y = lat, group = group)) +
geom_polygon(fill = NA, colour = "black")
Run Code Online (Sandbox Code Playgroud)
我对 SpatVector 对象没有经验,有更快的方法吗?
我知道 tidyterra 包(即 tidyterra::geom_spatvector())。
谢谢
sf对象也是data.frame,您可以使用 ggplot2 ( ) 提供的特定几何图形geom_sf()。R 中空间向量类之间的转换非常简单:
# From SpatVector to sf
sf::st_as_sf(x_spatvector)
# From sf to SpatVector
terra::vect(x_sf)
# To sp, although for most uses is recommended to stick to sf
as(x_sf, "Spatial")
Run Code Online (Sandbox Code Playgroud)
因此,如果 ypu 只需要绘制空间对象,为什么不使用ggplot2::geom_sf()/tidyterra::geom_spatvector()?将对象转换为数据框以进行绘图似乎只是来回,除非您有充分的理由这样做。
参见代表:
library(geodata)
#> Loading required package: terra
#> terra 1.6.17
library(ggplot2)
boundary_GB <- geodata::gadm(country = "GB", path = tempdir(), resolution = 2, level = 1)
class(boundary_GB)
#> [1] "SpatVector"
#> attr(,"package")
#> [1] "terra"
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
boundary_GB_sf <- st_as_sf(boundary_GB)
class(boundary_GB_sf)
#> [1] "sf" "data.frame"
# Is already a data.frame
# sf with geom_sf
ggplot(boundary_GB_sf) +
geom_sf(fill = NA, colour = "black")
Run Code Online (Sandbox Code Playgroud)

# Spatvector with tidyterra
library(tidyterra)
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:terra':
#>
#> intersect, union
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> Loading required package: tibble
#> Loading required package: tidyr
#>
#> Attaching package: 'tidyr'
#> The following object is masked from 'package:terra':
#>
#> extract
ggplot() +
geom_spatvector(data = boundary_GB, fill = NA, colour = "black")
Run Code Online (Sandbox Code Playgroud)

创建于 2022-10-05,使用reprex v2.0.2
| 归档时间: |
|
| 查看次数: |
1269 次 |
| 最近记录: |