Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

tidyverse and ggplot2 methods for terra spatial objects

License

NotificationsYou must be signed in to change notification settings

dieghernan/tidyterra

Repository files navigation

CRAN statusCRAN resultsDownloadsDOIR-CMD-checkR-hubcodecovCodeFactorr-universeProject Status: Active – The project has reached a stable, usable state and is being actively developed.Stack Exchange questionsWorks with terra-develWorks with sf-develWorks with ggplot2-develWorks with dplyr and readr-devel

The goal oftidyterra is to provide common methods of thetidyverse packages forobjects created with theterra package:SpatRaster andSpatVector. It also providesgeoms for plottingthese objects withggplot2.

Please citetidyterra as:

Hernangómez, D., (2023). Using the tidyverse with terra objects: thetidyterra package.Journal of Open Source Software,8(91), 5751,https://doi.org/10.21105/joss.05751.

A BibTeX entry for LaTeX users is:

@article{Hernangómez2023,doi ={10.21105/joss.05751},url ={https://doi.org/10.21105/joss.05751},year ={2023},publisher ={The Open Journal},volume ={8},number ={91},pages ={5751},author ={Diego Hernangómez},title ={Using the {tidyverse} with {terra} objects: the {tidyterra} package},journal ={Journal of Open Source Software}}

Overview

Full manual of the most recent release oftidyterra onCRAN isonline:https://dieghernan.github.io/tidyterra/

tidyverse methods implemented ontidyterra works differentlydepending on the type ofSpat* object:

  • SpatVector: the methods are implemented usingterra::as.data.frame() coercion. Rows correspond to geometries andcolumns correspond to attributes of the geometry.

  • SpatRaster: The implementation onSpatRaster objects differs,since the methods could be applied to layers or to cells.tidyterra overall approach is to treat the layers as columns of atibble and the cells as rows (i.e. select(SpatRaster, 1) wouldselect the first layer of aSpatRaster).

The methods implemented return the same type of object used as input,unless the expected behavior of the method is to return another type ofobject, (for example,as_tibble() would return atibble).

Current methods and functions provided bytidyterra are:

tidyverse methodSpatVectorSpatRaster
tibble::as_tibble()✔️✔️
dplyr::select()✔️✔️ Select layers
dplyr::mutate()✔️✔️ Create /modify layers
dplyr::transmute()✔️✔️
dplyr::filter()✔️✔️ Modify cells values and (additionally) remove outer cells.
dplyr::slice()✔️✔️ Additional methods for slicing by row and column.
dplyr::pull()✔️✔️
dplyr::rename()✔️✔️
dplyr::relocate()✔️✔️
dplyr::distinct()✔️
dplyr::arrange()✔️
dplyr::glimpse()✔️✔️
dplyr::inner_join() family✔️
dplyr::summarise()✔️
dplyr::group_by() family✔️
dplyr::rowwise()✔️
dplyr::count(),tally()✔️
dplyr::bind_cols() /dplyr::bind_rows()✔️ asbind_spat_cols() /bind_spat_rows()
tidyr::drop_na()✔️✔️ Remove cell values withNA on any layer. Additionally, outer cells withNA are removed.
tidyr::replace_na()✔️✔️
tidyr::fill()✔️
tidyr::pivot_longer()✔️
tidyr::pivot_wider()✔️
ggplot2::autoplot()✔️✔️
ggplot2::fortify()✔️ tosf viasf::st_as_sf()To atibble with coordinates.
ggplot2::geom_*()✔️geom_spatvector()✔️geom_spatraster() andgeom_spatraster_rgb().

❗ A note on performance

tidyterra is conceived as a user-friendly wrapper ofterra usingthetidyverse methods and verbs. This approach therefore has acost in terms of performance.

If you are aheavy user ofterra or you need to work withbigraster files,terra is much more focused on terms of performance.When possible, each function oftidyterra references to itsequivalent onterra.

As a rule of thumb if your raster has less than 10.000.000 data slotscounting cells and layers(i.e. terra::ncell(your_rast)*terra::nlyr(your_rast) < 10e6) you aregood to go withtidyterra.

When plotting rasters, resampling is performed automatically (asterra::plot() does, see the help page). You can adjust this with themaxcell parameter.

Installation

Installtidyterra fromCRAN:

install.packages("tidyterra")

You can install the development version oftidyterra like so:

# install.packages("pak")pak::pak("dieghernan/tidyterra")

Alternatively, you can installtidyterra using ther-universe:

# Enable this universeinstall.packages("tidyterra",repos= c("https://dieghernan.r-universe.dev","https://cloud.r-project.org"))

Example

SpatRasters

This is a basic example which shows you how to manipulate and plotSpatRaster objects:

library(tidyterra)library(terra)# Temperaturesrastertemp<- rast(system.file("extdata/cyl_temp.tif",package="tidyterra"))rastertemp#> class       : SpatRaster#> dimensions  : 87, 118, 3  (nrow, ncol, nlyr)#> resolution  : 3881.255, 3881.255  (x, y)#> extent      : -612335.4, -154347.3, 4283018, 4620687  (xmin, xmax, ymin, ymax)#> coord. ref. : World_Robinson#> source      : cyl_temp.tif#> names       :   tavg_04,   tavg_05,  tavg_06#> min values  :  1.885463,  5.817587, 10.46338#> max values  : 13.283829, 16.740898, 21.11378# Renamerastertemp<-rastertemp %>%  rename(April=tavg_04,May=tavg_05,June=tavg_06)# Facet all layerslibrary(ggplot2)ggplot()+  geom_spatraster(data=rastertemp)+  facet_wrap(~lyr,ncol=2)+  scale_fill_whitebox_c(palette="muted",labels=scales::label_number(suffix="º"),n.breaks=12,guide= guide_legend(reverse=TRUE)  )+  labs(fill="",title="Average temperature in Castille and Leon (Spain)",subtitle="Months of April, May and June"  )

# Create maximum differences of two monthsvariation<-rastertemp %>%  mutate(diff=June-May) %>%  select(variation=diff)# Add also a overlay of a SpatVectorprov<- vect(system.file("extdata/cyl.gpkg",package="tidyterra"))ggplot(prov)+  geom_spatraster(data=variation)+  geom_spatvector(fill=NA)+  scale_fill_whitebox_c(palette="deep",direction=-1,labels=scales::label_number(suffix="º"),n.breaks=5  )+  theme_minimal()+  coord_sf(crs=25830)+  labs(fill="Variation",title="Variation of Temperature in Castile and León (Spain)",subtitle="Average Temperatures: June vs. May"  )

tidyterra also provides a geom for plotting RGBSpatRaster tileswithggplot2:

rgb_tile<- rast(system.file("extdata/cyl_tile.tif",package="tidyterra"))plot<- ggplot(prov)+  geom_spatraster_rgb(data=rgb_tile)+  geom_spatvector(fill=NA)+  theme_light()plot

# Automatically recognizes and applies coord_sf() for spatial data.plot+# Change the CRS and datum (useful for relabeling graticules).  coord_sf(crs=3857,datum=3857)

tidyterra provides specific scales for plotting hypsometric mapswithggplot2:

asia<- rast(system.file("extdata/asia.tif",package="tidyterra"))terra::plot(asia)

ggplot()+  geom_spatraster(data=asia)+  scale_fill_hypso_tint_c(palette="gmt_globe",labels=scales::label_number(),# Further refinementsbreaks= c(-10000,-5000,0,2000,5000,8000),guide= guide_colorbar(reverse=TRUE)  )+  labs(fill="elevation (m)",title="Hypsometric map of Asia"  )+  theme(legend.position="bottom",legend.title.position="top",legend.key.width= rel(3),legend.ticks= element_line(colour="black",linewidth=0.3),legend.direction="horizontal"  )

SpatVectors

This is a basic example which shows you how to manipulate and plotSpatVector objects:

vect(system.file("ex/lux.shp",package="terra")) %>%  mutate(pop_dens=POP/AREA) %>%  glimpse() %>%  autoplot(aes(fill=pop_dens))+  scale_fill_whitebox_c(palette="pi_y_g")+  labs(fill="population per km2",title="Population density of Luxembourg",subtitle="By canton"  )#> #  A SpatVector 12 x 7#> #  Geometry type: Polygons#> #  Geodetic CRS: lon/lat WGS 84 (EPSG:4326)#> #  Extent (x / y) : ([5° 44' 38.9" E / 6° 31' 41.71" E] , [49° 26' 52.11" N / 50° 10' 53.84" N])#>#> $ ID_1     <dbl> 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3#> $ NAME_1   <chr> "Diekirch", "Diekirch", "Diekirch", "Diekirch", "Diekirch", "…#> $ ID_2     <dbl> 1, 2, 3, 4, 5, 6, 7, 12, 8, 9, 10, 11#> $ NAME_2   <chr> "Clervaux", "Diekirch", "Redange", "Vianden", "Wiltz", "Echte…#> $ AREA     <dbl> 312, 218, 259, 76, 263, 188, 129, 210, 185, 251, 237, 233#> $ POP      <dbl> 18081, 32543, 18664, 5163, 16735, 18899, 22366, 29828, 48187,…#> $ pop_dens <dbl> 57.95192, 149.27982, 72.06178, 67.93421, 63.63118, 100.52660,…

I need your feedback

Please leave your feedback or open an issue onhttps://github.com/dieghernan/tidyterra/issues.

Need help?

Check ourFAQs oropen a newissue!

You can also ask inStack Overflow usingthe tag[tidyterra].

Acknowledgement

tidyterraggplot2 geoms are based onggspatialimplementation, byDewey Dunningtonandggspatialcontributors.

Contributors

All contributions to this project are gratefully acknowledged using theallcontributors packagefollowing theallcontributorsspecification. Contributions of any kind are welcome!

Code


dieghernan

dramanica

Fan-iX

teunbrand

Issue Authors


Nowosad

schonhose

DidDrog11

sraul1

aloboa

kadyb

Shrubner

kdizzard

nipnipj

tigerwang1998

Edward62

kongdd

rhgof

pvjeetze

Yingjie4Science

mikejohnson51

danbebber

elgabbas

edzer

GuiSPinto

zzzqiii

mengjiezhang4ds

Beedmoser

claudehspencer

Maschette

frzambra

toihr

Breeze-Hu

beausoleilmo

Issue Contributors


twest820

stantis

rhijmans

HRodenhizer

Rapsodia86

rsbivand

[8]ページ先頭

©2009-2025 Movatter.jp