| Title: | 'tidyverse' Methods and 'ggplot2' Helpers for 'terra' Objects |
|---|---|
| Description: | Provides common 'tidyverse' methods for 'SpatRaster' and 'SpatVector' objects created by the 'terra' package, plus 'ggplot2' geoms for visualizing those objects. |
| Authors: | Diego Hernangómez [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-8457-4658>), Dewey Dunnington [ctb] (ORCID: <https://orcid.org/0000-0002-9415-4582>, for ggspatial code), ggplot2 authors [cph] (for contour code), Andrea Manica [ctb] (ORCID: <https://orcid.org/0000-0003-1895-450X>) |
| Maintainer: | Diego Hernangómez <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.1.0.9000 |
| Built: | 2026-06-03 13:21:01 UTC |
| Source: | https://github.com/dieghernan/tidyterra |
SpatVector using column valuesarrange.SpatVector() orders the geometries of a SpatVector by the
values of selected columns.
## S3 method for class 'SpatVector' arrange(.data, ..., .by_group = FALSE, .locale = NULL)## S3 method for class 'SpatVector' arrange(.data, ..., .by_group = FALSE, .locale = NULL)
.data |
A |
... |
< |
.by_group |
If |
.locale |
The locale to sort character vectors in.
The C locale is not the same as English locales, such as |
A SpatVector object.
Implementation of the generic dplyr::arrange() function for
SpatVector class.
Other single table verbs:
filter.Spat,
mutate.Spat,
reframe.SpatVector(),
rename.Spat,
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on rows:
distinct.SpatVector(),
filter.Spat,
rows.SpatVector,
slice.Spat
Other dplyr methods:
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) library(dplyr) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Single variable v |> arrange(desc(iso2)) # Two variables v |> mutate(even = as.double(cpro) %% 2 == 0) |> arrange(desc(even), desc(iso2)) # With new variables v |> mutate(area_geom = terra::expanse(v)) |> arrange(area_geom)library(terra) library(dplyr) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Single variable v |> arrange(desc(iso2)) # Two variables v |> mutate(even = as.double(cpro) %% 2 == 0) |> arrange(desc(even), desc(iso2)) # With new variables v |> mutate(area_geom = terra::expanse(v)) |> arrange(area_geom)
SpatRaster
as_coordinates() can be used to obtain the position of each cell on the
SpatRaster matrix.
as_coordinates(x, as.raster = FALSE)as_coordinates(x, as.raster = FALSE)
x |
A |
as.raster |
If |
A tibble or a SpatRaster (if as.raster = TRUE) with
the same number of rows (or cells) as the number of cells in x.
When as.raster = TRUE the resulting SpatRaster has the same CRS,
extension and resolution as x.
Coercing objects:
as_sf(),
as_spatraster(),
as_spatvector(),
as_tibble.Spat,
fortify.Spat,
tidy.Spat
library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) as_coordinates(r) as_coordinates(r, as.raster = TRUE) as_coordinates(r, as.raster = TRUE) |> plot()library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) as_coordinates(r) as_coordinates(r, as.raster = TRUE) as_coordinates(r, as.raster = TRUE) |> plot()
SpatVector to a sf objectas_sf() coerces a SpatVector into an sf object. It wraps
sf::st_as_sf() and preserves groups created with
group_by.SpatVector().
as_sf(x, ...)as_sf(x, ...)
x |
A |
... |
Additional arguments passed on to |
A sf object with an additional tbl_df class for
pretty printing.
Coercing objects:
as_coordinates(),
as_spatraster(),
as_spatvector(),
as_tibble.Spat,
fortify.Spat,
tidy.Spat
library(terra) f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- terra::vect(f) # This is ungrouped v is_grouped_spatvector(v) # Get an ungrouped data a_sf <- as_sf(v) dplyr::is_grouped_df(a_sf) # Grouped v$gr <- c("C", "A", "A", "B", "A", "B", "B") v$gr2 <- rep(c("F", "G", "F"), 3) gr_v <- group_by(v, gr, gr2) gr_v is_grouped_spatvector(gr_v) group_data(gr_v) # A sf a_gr_sf <- as_sf(gr_v) dplyr::is_grouped_df(a_gr_sf) group_data(a_gr_sf)library(terra) f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- terra::vect(f) # This is ungrouped v is_grouped_spatvector(v) # Get an ungrouped data a_sf <- as_sf(v) dplyr::is_grouped_df(a_sf) # Grouped v$gr <- c("C", "A", "A", "B", "A", "B", "B") v$gr2 <- rep(c("F", "G", "F"), 3) gr_v <- group_by(v, gr, gr2) gr_v is_grouped_spatvector(gr_v) group_data(gr_v) # A sf a_gr_sf <- as_sf(gr_v) dplyr::is_grouped_df(a_gr_sf) group_data(a_gr_sf)
SpatRaster
as_spatraster() converts a data frame or tibble into a
SpatRaster. It wraps the terra::rast() S4 method for signature
data.frame.
as_spatraster(x, ..., xycols = 1:2, crs = "", digits = 6)as_spatraster(x, ..., xycols = 1:2, crs = "", digits = 6)
x |
A tibble or data frame. |
... |
Additional arguments passed on to |
xycols |
A vector of integers of length 2 determining the position of
the columns that hold the |
crs |
A CRS in several formats (PROJ.4, WKT, EPSG code, etc.) or a
spatial object from sf or terra that
includes the target coordinate reference system. See |
digits |
Integer to set the precision for detecting whether points are on a regular grid (a low number of digits is a low precision). |
If no crs is provided and the tibble has been created with the method
as_tibble.SpatRaster(), the crs is inferred from
attr(x, "crs").
A SpatRaster.
terra::rast() (see S4 method for signature data.frame).
pull_crs() for retrieving CRS and the corresponding utils sf::st_crs()
and terra::crs().
Coercing objects:
as_coordinates(),
as_sf(),
as_spatvector(),
as_tibble.Spat,
fortify.Spat,
tidy.Spat
library(terra) r <- rast(matrix(1:90, ncol = 3), crs = "EPSG:3857") r # Create tibble as_tbl <- as_tibble(r, xy = TRUE) as_tbl # From tibble newrast <- as_spatraster(as_tbl, crs = "EPSG:3857") newrastlibrary(terra) r <- rast(matrix(1:90, ncol = 3), crs = "EPSG:3857") r # Create tibble as_tbl <- as_tibble(r, xy = TRUE) as_tbl # From tibble newrast <- as_spatraster(as_tbl, crs = "EPSG:3857") newrast
SpatVector
as_spatvector() turns an existing object into a SpatVector. It wraps the
terra::vect() S4 method for the data.frame signature.
as_spatvector(x, ...) ## S3 method for class 'data.frame' as_spatvector(x, ..., geom = c("lon", "lat"), crs = "") ## S3 method for class 'sf' as_spatvector(x, ...) ## S3 method for class 'sfc' as_spatvector(x, ...) ## S3 method for class 'SpatVector' as_spatvector(x, ...)as_spatvector(x, ...) ## S3 method for class 'data.frame' as_spatvector(x, ..., geom = c("lon", "lat"), crs = "") ## S3 method for class 'sf' as_spatvector(x, ...) ## S3 method for class 'sfc' as_spatvector(x, ...) ## S3 method for class 'SpatVector' as_spatvector(x, ...)
x |
|
... |
Additional arguments passed on to |
geom |
Character vector naming the fields that contain the geometry
data. Use two names for point coordinates ( |
crs |
A CRS in several formats (PROJ.4, WKT, EPSG code, etc.) or a
spatial object from sf or terra that
includes the target coordinate reference system. See |
This function differs from terra::vect() in the following ways:
Rows with geometry values NA or "" are removed before conversion.
If x is a grouped data frame (see dplyr::group_by()), the grouping
variables are transferred and a grouped SpatVector is created (see
group_by.SpatVector()).
If no crs is provided and the tibble has been created with the method
as_tibble.SpatVector(), the crs is inferred from
attr(x, "crs").
It handles the conversion of EMPTY geometries between
sf and terra.
A SpatVector.
pull_crs() for retrieving CRS and the corresponding utils sf::st_crs()
and terra::crs().
Coercing objects:
as_coordinates(),
as_sf(),
as_spatraster(),
as_tibble.Spat,
fortify.Spat,
tidy.Spat
library(terra) v <- vect(matrix(1:80, ncol = 2), crs = "EPSG:3857") v$cat <- sample(LETTERS[1:4], size = nrow(v), replace = TRUE) v # Create tibble as_tbl <- as_tibble(v, geom = "WKT") as_tbl # From tibble newvect <- as_spatvector(as_tbl, geom = "geometry", crs = "EPSG:3857") newvectlibrary(terra) v <- vect(matrix(1:80, ncol = 2), crs = "EPSG:3857") v$cat <- sample(LETTERS[1:4], size = nrow(v), replace = TRUE) v # Create tibble as_tbl <- as_tibble(v, geom = "WKT") as_tbl # From tibble newvect <- as_spatvector(as_tbl, geom = "geometry", crs = "EPSG:3857") newvect
SpatRaster and SpatVector objects to tibblesas_tibble() methods for SpatRaster and SpatVector objects.
## S3 method for class 'SpatRaster' as_tibble( x, ..., xy = FALSE, na.rm = FALSE, .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet") ) ## S3 method for class 'SpatVector' as_tibble( x, ..., geom = NULL, .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet") )## S3 method for class 'SpatRaster' as_tibble( x, ..., xy = FALSE, na.rm = FALSE, .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet") ) ## S3 method for class 'SpatVector' as_tibble( x, ..., geom = NULL, .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet") )
x |
A |
... |
Arguments passed on to |
xy |
logical. If |
na.rm |
logical. If |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
geom |
character or NULL. If not NULL, either "WKT" or "HEX", to get the geometry included in Well-Known-Text or hexadecimal notation. If |
A tibble.
Implementation of the generic tibble::as_tibble() method.
SpatRaster and SpatVector
The returned tibble includes the CRS of the original object as an attribute
in WKT format (see pull_crs()).
When coercing SpatRaster objects to data frames, x and y are reserved
names for the geographic coordinates of each cell. terra also
allows layers with duplicated names.
When coercing a SpatRaster to a tibble, tidyterra may rename its
layers to avoid these issues. Specifically, layers may be renamed in the
following cases:
Layers with duplicated names.
When coercing to a tibble, if xy = TRUE, layers named x or
y are renamed.
When working with tidyverse methods (i.e. filter.SpatRaster()), the
same renaming happens.
tidyterra displays a message describing the renamed layers.
The same issue affects SpatVector objects with reserved names such as
geometry (when geom = c("WKT", "HEX")) and x, y (when
geom = "XY"). These names represent geometry columns in
terra::as.data.frame(). If geom is not NULL, the same renaming logic
described for SpatRaster also applies to SpatVector columns.
tibble::as_tibble(), terra::as.data.frame()
Coercing objects:
as_coordinates(),
as_sf(),
as_spatraster(),
as_spatvector(),
fortify.Spat,
tidy.Spat
library(terra) # SpatRaster f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) as_tibble(r, na.rm = TRUE) as_tibble(r, xy = TRUE) # SpatVector f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) as_tibble(v)library(terra) # SpatRaster f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) as_tibble(r, na.rm = TRUE) as_tibble(r, xy = TRUE) # SpatVector f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) as_tibble(v)
Spat* objectsautoplot() uses ggplot2 to draw plots like those
produced by terra::plot()/terra::plotRGB() in a single command.
## S3 method for class 'SpatRaster' autoplot( object, ..., rgb = NULL, use_coltab = NULL, facets = NULL, nrow = NULL, ncol = 2 ) ## S3 method for class 'SpatVector' autoplot(object, ...) ## S3 method for class 'SpatGraticule' autoplot(object, ...) ## S3 method for class 'SpatExtent' autoplot(object, ...)## S3 method for class 'SpatRaster' autoplot( object, ..., rgb = NULL, use_coltab = NULL, facets = NULL, nrow = NULL, ncol = 2 ) ## S3 method for class 'SpatVector' autoplot(object, ...) ## S3 method for class 'SpatGraticule' autoplot(object, ...) ## S3 method for class 'SpatExtent' autoplot(object, ...)
object |
A |
... |
Other arguments passed to |
rgb |
Logical. If |
use_coltab |
Logical. If |
facets |
Logical. If |
nrow, ncol
|
Number of rows and columns in the facet. |
Implementation of ggplot2::autoplot() method.
A ggplot2 layer
Implementation of the generic ggplot2::autoplot() method.
SpatRasterUses geom_spatraster() or geom_spatraster_rgb().
SpatVector, SpatGraticule and SpatExtent
Uses geom_spatvector(). Labels can be placed with geom_spatvector_text()
or geom_spatvector_label().
Other ggplot2 utils:
fortify.Spat,
geom_spat_contour,
geom_spatraster(),
geom_spatraster_rgb(),
ggspatvector,
stat_spat_coordinates()
Other ggplot2 methods:
fortify.Spat
file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) temp <- rast(file_path) library(ggplot2) autoplot(temp) # With a tile tile <- system.file("extdata/cyl_tile.tif", package = "tidyterra") |> rast() autoplot(tile) # With coltabs ctab <- system.file("extdata/cyl_era.tif", package = "tidyterra") |> rast() autoplot(ctab) # With vectors v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) autoplot(v) v |> autoplot(aes(fill = cpro)) + geom_spatvector_text(aes(label = iso2)) + coord_sf(crs = 25829)file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) temp <- rast(file_path) library(ggplot2) autoplot(temp) # With a tile tile <- system.file("extdata/cyl_tile.tif", package = "tidyterra") |> rast() autoplot(tile) # With coltabs ctab <- system.file("extdata/cyl_era.tif", package = "tidyterra") |> rast() autoplot(ctab) # With vectors v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) autoplot(v) v |> autoplot(aes(fill = cpro)) + geom_spatvector_text(aes(label = iso2)) + coord_sf(crs = 25829)
SpatVector, sf and data frame objects by columnBind any number of SpatVector, data frames and sf objects by column,
making a wider result. This is similar to do.call(cbind, data_frames).
Where possible prefer using a join to
combine SpatVector and data frame objects. bind_spat_cols()
binds the rows in order in which they appear so it is easy to create
meaningless results without realizing it.
bind_spat_cols( ..., .name_repair = c("unique", "universal", "check_unique", "minimal") )bind_spat_cols( ..., .name_repair = c("unique", "universal", "check_unique", "minimal") )
... |
Objects to combine. The first argument must be a |
.name_repair |
One of |
A SpatVector with the corresponding columns. The geometry and CRS
correspond to the first SpatVector of ....
cbind() method
Implementation of the dplyr::bind_cols() function for
SpatVector objects. Note that for the second and subsequent arguments on
..., the geometry is not cbinded and only the data frame-like columns
are kept.
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_rows.SpatVector,
cross_join.SpatVector(),
filter-joins.SpatVector,
mutate-joins.SpatVector,
nest_join.SpatVector(),
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) sv <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) df2 <- data.frame(letters = letters[seq_len(nrow(sv))]) # Data frame bind_spat_cols(sv, df2) # Another SpatVector bind_spat_cols(sv[1:2, ], sv[3:4, ]) # sf objects sfobj <- sf::read_sf(system.file("shape/nc.shp", package = "sf")) bind_spat_cols(sv[1:9, ], sfobj[1:9, ]) # Mixed end <- bind_spat_cols(sv, sfobj[seq_len(nrow(sv)), 1:2], df2) end glimpse(end) # Row sizes must be compatible when column-binding try(bind_spat_cols(sv, sfobj))library(terra) sv <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) df2 <- data.frame(letters = letters[seq_len(nrow(sv))]) # Data frame bind_spat_cols(sv, df2) # Another SpatVector bind_spat_cols(sv[1:2, ], sv[3:4, ]) # sf objects sfobj <- sf::read_sf(system.file("shape/nc.shp", package = "sf")) bind_spat_cols(sv[1:9, ], sfobj[1:9, ]) # Mixed end <- bind_spat_cols(sv, sfobj[seq_len(nrow(sv)), 1:2], df2) end glimpse(end) # Row sizes must be compatible when column-binding try(bind_spat_cols(sv, sfobj))
SpatVector, sf/sfc and data frame objects by rowBind any number of SpatVector, data frames and sf/sfc objects by row,
making a longer result. This is similar to do.call(rbind, data_frames),
but the output will contain all columns that appear in any of the inputs.
bind_spat_rows(..., .id = NULL)bind_spat_rows(..., .id = NULL)
... |
Objects to combine. The first argument must be a |
.id |
The name of an optional identifier column. Provide a string to create an output column that identifies each input. The column will use names if available, otherwise it will use positions. |
A SpatVector of the same type as the first element of ....
rbind() method
Implementation of the dplyr::bind_rows() function for
SpatVector objects.
The first argument should be a SpatVector. Each subsequent argument can be
a SpatVector, sf/sfc object or data frame:
If subsequent SpatVector/sf/sfc objects have a different CRS than the
first element, those elements are reprojected to the CRS of the
first element with a message.
If any element of ... is a tibble/data frame, the rows are column-bound
with empty geometries with a message.
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
cross_join.SpatVector(),
filter-joins.SpatVector,
mutate-joins.SpatVector,
nest_join.SpatVector(),
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v1 <- v[1, "cpro"] v2 <- v[3:5, c("name", "iso2")] # You can supply individual SpatVector as arguments: bind_spat_rows(v1, v2) # When you supply a column name with the `.id` argument, a new # column is created to link each row to its original data frame bind_spat_rows(v1, v2, .id = "id") # Use with sf sfobj <- sf::st_as_sf(v2[1, ]) sfobj bind_spat_rows(v1, sfobj) # Would reproject with a message on different CRS sfobj_3857 <- as_spatvector(sfobj) |> project("EPSG:3857") bind_spat_rows(v1, sfobj_3857) # And with data frames with a message data("mtcars") bind_spat_rows(v1, sfobj, mtcars, .id = "id2") # Use lists bind_spat_rows(list(v1[1, ], sfobj[1:2, ])) # Or named list combined with .id bind_spat_rows(list( SpatVector = v1[1, ], sf = sfobj[1, ], mtcars = mtcars[1, ] ), .id = "source")library(terra) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v1 <- v[1, "cpro"] v2 <- v[3:5, c("name", "iso2")] # You can supply individual SpatVector as arguments: bind_spat_rows(v1, v2) # When you supply a column name with the `.id` argument, a new # column is created to link each row to its original data frame bind_spat_rows(v1, v2, .id = "id") # Use with sf sfobj <- sf::st_as_sf(v2[1, ]) sfobj bind_spat_rows(v1, sfobj) # Would reproject with a message on different CRS sfobj_3857 <- as_spatvector(sfobj) |> project("EPSG:3857") bind_spat_rows(v1, sfobj_3857) # And with data frames with a message data("mtcars") bind_spat_rows(v1, sfobj, mtcars, .id = "id2") # Use lists bind_spat_rows(list(v1[1, ], sfobj[1:2, ])) # Or named list combined with .id bind_spat_rows(list( SpatVector = v1[1, ], sf = sfobj[1, ], mtcars = mtcars[1, ] ), .id = "source")
SpatRaster objectsTwo SpatRaster objects are compatible (in terms of combining layers) if the
CRS, extent and resolution are similar. In those cases you can combine the
objects simply as c(x, y).
This function compares those attributes informing of the results. See Solving issues section for minimal guidance.
compare_spatrasters(x, y, digits = 6)compare_spatrasters(x, y, digits = 6)
x, y
|
|
digits |
Integer to set the precision for comparing the extent and the resolution. |
A invisible logical TRUE/FALSE indicating if the SpatRaster objects are
compatible, plus an informative message flagging the issues found (if any).
On non-equal CRS, try terra::project().
On non-equal extent try terra::resample().
On non-equal resolution you can try terra::resample(),
terra::aggregate() or terra::disagg().
Other helpers:
is_grouped_spatvector(),
is_regular_grid(),
pull_crs()
library(terra) x <- rast(matrix(1:90, ncol = 3), crs = "EPSG:3857") # Nothing compare_spatrasters(x, x) # Different crs y_nocrs <- x crs(y_nocrs) <- NA compare_spatrasters(x, y_nocrs) # Different extent compare_spatrasters(x, x[1:10, , drop = FALSE]) # Different resolution y_newres <- x res(y_newres) <- res(x) / 2 compare_spatrasters(x, y_newres) # Everything compare_spatrasters(x, project(x, "epsg:3035"))library(terra) x <- rast(matrix(1:90, ncol = 3), crs = "EPSG:3857") # Nothing compare_spatrasters(x, x) # Different crs y_nocrs <- x crs(y_nocrs) <- NA compare_spatrasters(x, y_nocrs) # Different extent compare_spatrasters(x, x[1:10, , drop = FALSE]) # Different resolution y_newres <- x res(y_newres) <- res(x) / 2 compare_spatrasters(x, y_newres) # Everything compare_spatrasters(x, project(x, "epsg:3035"))
SpatVector
complete() turns implicit missing combinations in a SpatVector
into explicit rows while preserving geometry and spatial metadata.
## S3 method for class 'SpatVector' complete(data, ..., fill = list(), explicit = TRUE)## S3 method for class 'SpatVector' complete(data, ..., fill = list(), explicit = TRUE)
data |
A |
... |
<
When used with factors, When used with continuous variables, you may need to fill in values
that do not appear in the data: to do so use expressions like
|
fill |
A named list that for each variable supplies a single value to
use instead of |
explicit |
Should both implicit (newly created) and explicit
(pre-existing) missing values be filled by |
A SpatVector object.
Implementation of the generic tidyr::complete() method.
SpatVectorcomplete() preserves the geometry column while expanding missing
combinations. New combinations receive empty geometries.
Other tidyr verbs for handling missing values:
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
replace_na.Spat
Other tidyr methods:
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v <- dplyr::mutate(v, grp = ifelse(iso2 %in% c("ES-AV", "ES-BU"), "a", "b")) complete(v, grp, tidyr::nesting(iso2, name)) |> glimpse()v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v <- dplyr::mutate(v, grp = ifelse(iso2 %in% c("ES-AV", "ES-BU"), "a", "b")) complete(v, grp, tidyr::nesting(iso2, name)) |> glimpse()
SpatVector groupcount() lets you quickly count the unique values of one or more variables:
df |> count(a, b) is roughly equivalent to
df |> group_by(a, b) |> summarise(n = n()). count() is paired with
tally(), a lower-level helper that is equivalent to
df |> summarise(n = n()). Supply wt to perform weighted counts,
switching the summary from n = n() to n = sum(wt).
add_count() is equivalent to count() but use mutate() instead of
summarise() so that it adds a new column with group-wise counts.
## S3 method for class 'SpatVector' count( x, ..., wt = NULL, sort = FALSE, name = NULL, .drop = deprecated(), .dissolve = TRUE ) ## S3 method for class 'SpatVector' tally(x, wt = NULL, sort = FALSE, name = NULL) ## S3 method for class 'SpatVector' add_count(x, ..., wt = NULL, sort = FALSE, name = NULL, .drop = deprecated())## S3 method for class 'SpatVector' count( x, ..., wt = NULL, sort = FALSE, name = NULL, .drop = deprecated(), .dissolve = TRUE ) ## S3 method for class 'SpatVector' tally(x, wt = NULL, sort = FALSE, name = NULL) ## S3 method for class 'SpatVector' add_count(x, ..., wt = NULL, sort = FALSE, name = NULL, .drop = deprecated())
x |
A |
... |
< |
wt |
<
|
sort |
If |
name |
The name of the new column in the output. If omitted, it will default to |
.drop |
|
.dissolve |
Logical. If |
A SpatVector object with updated grouping metadata.
Implementation of the generic dplyr::count() methods for SpatVector
objects.
tally() will always return a disaggregated geometry while count() can
handle this. See also summarise.SpatVector().
dplyr::count(), dplyr::tally()
Other dplyr verbs that operate on group of rows:
group_by.SpatVector(),
reframe.SpatVector(),
rowwise.SpatVector(),
summarise.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) f <- system.file("ex/lux.shp", package = "terra") p <- vect(f) p |> count(NAME_1, sort = TRUE) p |> count(pop = ifelse(POP < 20000, "A", "B")) # tally() is a lower-level function that assumes you've done the grouping p |> tally() p |> group_by(NAME_1) |> tally() # Dissolve geometries by default library(ggplot2) p |> count(NAME_1) |> ggplot() + geom_spatvector(aes(fill = n)) # Opt out p |> count(NAME_1, .dissolve = FALSE, sort = TRUE) |> ggplot() + geom_spatvector(aes(fill = n))library(terra) f <- system.file("ex/lux.shp", package = "terra") p <- vect(f) p |> count(NAME_1, sort = TRUE) p |> count(pop = ifelse(POP < 20000, "A", "B")) # tally() is a lower-level function that assumes you've done the grouping p |> tally() p |> group_by(NAME_1) |> tally() # Dissolve geometries by default library(ggplot2) p |> count(NAME_1) |> ggplot() + geom_spatvector(aes(fill = n)) # Opt out p |> count(NAME_1, .dissolve = FALSE, sort = TRUE) |> ggplot() + geom_spatvector(aes(fill = n))
A tibble including the color map of
4 gradient palettes.
All palettes also include a definition of color limits in terms of elevation
(meters) that can be used with ggplot2::scale_fill_gradientn().
A tibble of 41 rows and 6 columns with the following fields:
Name of the palette.
Recommended elevation limit (in meters) for each color.
Value of the red channel (RGB color mode).
Value of the green channel (RGB color mode).
Value of the blue channel (RGB color mode).
Hex code of the color.
From Patterson & Jenny (2011):
More recently, the role and design of hypsometric tints have come under scrutiny. One reason for this is the concern that people misread elevation colors as climate or vegetation information. Cross-blended hypsometric tints, introduced in 2009, are a partial solution to this problem. They use variable lowland colors customized to match the differing natural environments of world regions, which merge into one another.
Derived from:
Patterson, T., & Jenny, B. (2011). The Development and Rationale of Cross-blended Hypsometric Tints. Cartographic Perspectives, (69), 31-46. doi:10.14714/CP69.20.
Other datasets:
grass_db,
hypsometric_tints_db,
princess_db,
volcano2
data("cross_blended_hypsometric_tints_db") cross_blended_hypsometric_tints_db # Select a palette warm <- cross_blended_hypsometric_tints_db |> filter(pal == "warm_humid") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = warm$hex) # Use with limits p + scale_fill_gradientn( colors = warm$hex, values = scales::rescale(warm$limit), limit = range(warm$limit), na.value = "lightblue" )data("cross_blended_hypsometric_tints_db") cross_blended_hypsometric_tints_db # Select a palette warm <- cross_blended_hypsometric_tints_db |> filter(pal == "warm_humid") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = warm$hex) # Use with limits p + scale_fill_gradientn( colors = warm$hex, values = scales::rescale(warm$limit), limit = range(warm$limit), na.value = "lightblue" )
SpatVector objectsCross joins match each row in x to every row in y.
See dplyr::cross_join() for details.
## S3 method for class 'SpatVector' cross_join(x, y, ..., copy = FALSE, suffix = c(".x", ".y"))## S3 method for class 'SpatVector' cross_join(x, y, ..., copy = FALSE, suffix = c(".x", ".y"))
x |
A |
y |
A data frame or other object coercible to a data frame. If a
|
... |
Additional arguments passed on to |
copy |
If |
suffix |
If there are non-joined duplicate variables in |
A SpatVector object.
Implementation of the generic dplyr::cross_join() method.
SpatVectorThe geometry column has sticky behavior. The result repeats each geometry in
x once for every row in y.
If y has a column named geometry, it is treated as a regular attribute
and receives the suffix from suffix.
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
bind_rows.SpatVector,
filter-joins.SpatVector,
mutate-joins.SpatVector,
nest_join.SpatVector(),
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) labels <- data.frame(period = c("past", "present")) cross_join(v, labels)v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) labels <- data.frame(period = c("past", "present")) cross_join(v, labels)
SpatVector objectsKeep only unique/distinct rows and geometries from a SpatVector.
## S3 method for class 'SpatVector' distinct(.data, ..., .keep_all = FALSE)## S3 method for class 'SpatVector' distinct(.data, ..., .keep_all = FALSE)
.data |
A |
... |
< |
.keep_all |
If |
A SpatVector object.
Implementation of the generic dplyr::distinct() method.
SpatVectorYou can remove duplicate geometries by passing the reserved name
geometry to .... See Examples.
dplyr::distinct(), terra::unique()
Other dplyr verbs that operate on rows:
arrange.SpatVector(),
filter.Spat,
rows.SpatVector,
slice.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) v <- vect(system.file("ex/lux.shp", package = "terra")) # Create a vector with dups v <- v[sample(seq_len(nrow(v)), 100, replace = TRUE), ] v$gr <- sample(LETTERS[1:3], 100, replace = TRUE) # All duplicates ex1 <- distinct(v) ex1 nrow(ex1) # Duplicates by NAME_1 ex2 <- distinct(v, gr) ex2 nrow(ex2) # Same but keeping all cols ex2b <- distinct(v, gr, .keep_all = TRUE) ex2b nrow(ex2b) # Unique geometries ex3 <- distinct(v, geometry) ex3 nrow(ex3) # Same as terra::unique() terra::unique(ex3) # Unique keeping info distinct(v, geometry, .keep_all = TRUE)library(terra) v <- vect(system.file("ex/lux.shp", package = "terra")) # Create a vector with dups v <- v[sample(seq_len(nrow(v)), 100, replace = TRUE), ] v$gr <- sample(LETTERS[1:3], 100, replace = TRUE) # All duplicates ex1 <- distinct(v) ex1 nrow(ex1) # Duplicates by NAME_1 ex2 <- distinct(v, gr) ex2 nrow(ex2) # Same but keeping all cols ex2b <- distinct(v, gr, .keep_all = TRUE) ex2b nrow(ex2b) # Unique geometries ex3 <- distinct(v, geometry) ex3 nrow(ex3) # Same as terra::unique() terra::unique(ex3) # Unique keeping info distinct(v, geometry, .keep_all = TRUE)
Spat* objects containing missing valuesSpatVector: drop_na() method drops geometries where any attribute
specified by ... contains a missing value.
SpatRaster: drop_na() method drops cells where any layer specified by
... contains a missing value.
## S3 method for class 'SpatVector' drop_na(data, ...) ## S3 method for class 'SpatRaster' drop_na(data, ...)## S3 method for class 'SpatVector' drop_na(data, ...) ## S3 method for class 'SpatRaster' drop_na(data, ...)
data |
A |
... |
< |
A Spat* object of the same class as data. See Methods.
Implementation of the generic tidyr::drop_na() method.
SpatVectorThe implementation of this method is performed on a by-attribute basis,
meaning that NA values are assessed on the attributes (columns) of each
vector (rows). The result is a SpatVector with potentially fewer
geometries than the input.
SpatRasterThe implementation of drop_na().SpatRaster can be understood as a
masking method based on the values of the layers (see
terra::mask()).
SpatRaster layers are considered as columns and SpatRaster cells as rows,
so rows (cells) with any NA value on any layer become NA. You can also
mask the cells (rows) based on the values of specific
layers (columns).
drop_na() effectively removes outer cells that are NA (see
terra::trim()), so the extent of the resulting object may differ from the
extent of the input (see terra::resample() for more information).
Check the Examples to have a better understanding of this method.
Visit https://github.com/dieghernan/tidyterra/issues. The implementation
of this method for SpatRaster may change in the future.
Other tidyr verbs for handling missing values:
complete.SpatVector(),
expand.SpatVector(),
fill.SpatVector(),
replace_na.Spat
Other tidyr methods:
complete.SpatVector(),
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
library(terra) f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- terra::vect(f) # Add NAs v <- v |> mutate(iso2 = ifelse(cpro <= "09", NA, cpro)) # Init plot(v, col = "red") # Mask with lyr.1 v |> drop_na(iso2) |> plot(col = "red") # SpatRaster method r <- rast( crs = "EPSG:3857", extent = c(0, 10, 0, 10), nlyr = 3, resolution = c(2.5, 2.5) ) terra::values(r) <- seq_len(ncell(r) * nlyr(r)) # Add NAs r[r > 13 & r < 22 | r > 31 & r < 45] <- NA # Init plot(r, nc = 3) # Mask with lyr.1 r |> drop_na(lyr.1) |> plot(nc = 3) # Mask with lyr.2 r |> drop_na(lyr.2) |> plot(nc = 3) # Mask with lyr.3 r |> drop_na(lyr.3) |> plot(nc = 3) # Auto-mask all layers r |> drop_na() |> plot(nc = 3)library(terra) f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- terra::vect(f) # Add NAs v <- v |> mutate(iso2 = ifelse(cpro <= "09", NA, cpro)) # Init plot(v, col = "red") # Mask with lyr.1 v |> drop_na(iso2) |> plot(col = "red") # SpatRaster method r <- rast( crs = "EPSG:3857", extent = c(0, 10, 0, 10), nlyr = 3, resolution = c(2.5, 2.5) ) terra::values(r) <- seq_len(ncell(r) * nlyr(r)) # Add NAs r[r > 13 & r < 22 | r > 31 & r < 45] <- NA # Init plot(r, nc = 3) # Mask with lyr.1 r |> drop_na(lyr.1) |> plot(nc = 3) # Mask with lyr.2 r |> drop_na(lyr.2) |> plot(nc = 3) # Mask with lyr.3 r |> drop_na(lyr.3) |> plot(nc = 3) # Auto-mask all layers r |> drop_na() |> plot(nc = 3)
SpatVector attribute combinationsexpand() returns a tibble with all combinations of selected attributes.
It does not return a SpatVector because newly created combinations do not
have a well-defined geometry. Use complete.SpatVector() when empty
geometries should be added explicitly.
## S3 method for class 'SpatVector' expand(data, ..., .name_repair = "check_unique")## S3 method for class 'SpatVector' expand(data, ..., .name_repair = "check_unique")
data |
A |
... |
<
When used with factors, When used with continuous variables, you may need to fill in values
that do not appear in the data: to do so use expressions like
|
.name_repair |
One of |
A tibble.
Implementation of the generic tidyr::expand() method.
SpatVectorThe output is a tibble with attribute combinations. Geometry is not preserved because new combinations do not have a well-defined geometry.
tidyr::expand(), complete.SpatVector()
Other tidyr verbs for handling missing values:
complete.SpatVector(),
drop_na.Spat,
fill.SpatVector(),
replace_na.Spat
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$grp <- rep(c("A", "B"), length.out = nrow(v)) expand(v, grp, cpro)v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$grp <- rep(c("A", "B"), length.out = nrow(v)) expand(v, grp, cpro)
SpatVector
Fills missing values in selected columns using the next or previous entry. This is useful in the common output format where values are not repeated, and are only recorded when they change.
## S3 method for class 'SpatVector' fill(data, ..., .by = NULL, .direction = c("down", "up", "downup", "updown"))## S3 method for class 'SpatVector' fill(data, ..., .by = NULL, .direction = c("down", "up", "downup", "updown"))
data |
A |
... |
< |
.by |
< |
.direction |
Direction in which to fill missing values. Currently either "down" (the default), "up", "downup" (i.e. first down and then up) or "updown" (first up and then down). |
A SpatVector object.
Implementation of the generic tidyr::fill() function for SpatVector.
SpatVector
With grouped SpatVector created by group_by.SpatVector(), fill() will
be applied within each group, meaning that it won't fill across group
boundaries.
Other tidyr verbs for handling missing values:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
replace_na.Spat
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
library(dplyr) lux <- terra::vect(system.file("ex/lux.shp", package = "terra")) # Leave some blanks for demo purposes lux_blnk <- lux |> mutate(NAME_1 = if_else(NAME_1 != NAME_2, NA, NAME_2)) as_tibble(lux_blnk) # `fill()` defaults to replacing missing data from top to bottom lux_blnk |> fill(NAME_1) |> as_tibble() # direction = "up" lux_blnk |> fill(NAME_1, .direction = "up") |> as_tibble() # Grouping and downup - will restore the initial state lux_blnk |> group_by(ID_1) |> fill(NAME_1, .direction = "downup") |> as_tibble()library(dplyr) lux <- terra::vect(system.file("ex/lux.shp", package = "terra")) # Leave some blanks for demo purposes lux_blnk <- lux |> mutate(NAME_1 = if_else(NAME_1 != NAME_2, NA, NAME_2)) as_tibble(lux_blnk) # `fill()` defaults to replacing missing data from top to bottom lux_blnk |> fill(NAME_1) |> as_tibble() # direction = "up" lux_blnk |> fill(NAME_1, .direction = "up") |> as_tibble() # Grouping and downup - will restore the initial state lux_blnk |> group_by(ID_1) |> fill(NAME_1, .direction = "downup") |> as_tibble()
SpatVector objectsFiltering joins filter rows from x based on the presence or absence of
matches in y:
semi_join() return all rows from x with a match in y.
anti_join() return all rows from x without a match in y.
See dplyr::semi_join() for details.
## S3 method for class 'SpatVector' semi_join(x, y, by = NULL, copy = FALSE, ...) ## S3 method for class 'SpatVector' anti_join(x, y, by = NULL, copy = FALSE, ...)## S3 method for class 'SpatVector' semi_join(x, y, by = NULL, copy = FALSE, ...) ## S3 method for class 'SpatVector' anti_join(x, y, by = NULL, copy = FALSE, ...)
x |
A |
y |
A data frame or other object coercible to a data frame. If a
|
by |
A join specification created with If To join on different variables between To join by multiple variables, use a
For simple equality joins, you can alternatively specify a character vector
of variable names to join by. For example, To perform a cross-join, generating all combinations of |
copy |
If |
... |
Other parameters passed onto methods. |
A SpatVector object.
Implementation of the generic dplyr::semi_join() family
SpatVectorThe geometry column has sticky behavior. This means that the result always
has the geometry of x for the records that match the join conditions.
dplyr::semi_join(), dplyr::anti_join(), terra::merge()
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
bind_rows.SpatVector,
cross_join.SpatVector(),
mutate-joins.SpatVector,
nest_join.SpatVector(),
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) library(ggplot2) # Vector v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # A data frame df <- data.frame( cpro = sprintf("%02d", 1:10), x = runif(10), y = runif(10), letter = rep_len(LETTERS[1:3], length.out = 10) ) v # Semi join semi <- v |> semi_join(df) semi autoplot(semi, aes(fill = iso2)) + labs(title = "Semi Join") # Anti join anti <- v |> anti_join(df) anti autoplot(anti, aes(fill = iso2)) + labs(title = "Anti Join")library(terra) library(ggplot2) # Vector v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # A data frame df <- data.frame( cpro = sprintf("%02d", 1:10), x = runif(10), y = runif(10), letter = rep_len(LETTERS[1:3], length.out = 10) ) v # Semi join semi <- v |> semi_join(df) semi autoplot(semi, aes(fill = iso2)) + labs(title = "Semi Join") # Anti join anti <- v |> anti_join(df) anti autoplot(anti, aes(fill = iso2)) + labs(title = "Anti Join")
Spat* objectsThese functions subset a data frame by applying the expressions in ...
to determine which rows should be kept (for filter()) or dropped (for
filter_out()).
Multiple conditions can be supplied separated by a comma. These will be
combined with the & operator. To combine comma separated conditions using
| instead, wrap them in dplyr::when_any().
Both filter() and filter_out() treat NA like FALSE. This subtle
behavior can affect how you write your conditions when missing values are
involved. See dplyr::filter().
You can filter a SpatRaster by its geographic coordinates.
Use filter(.data, x > 42). Note that x and y are reserved
names on terra, since they refer to the geographic coordinates of
the layer.
See Examples and section About layer names on as_tibble.Spat().
## S3 method for class 'SpatRaster' filter(.data, ..., .preserve = FALSE, .keep_extent = TRUE) ## S3 method for class 'SpatVector' filter(.data, ..., .by = NULL, .preserve = FALSE) ## S3 method for class 'SpatVector' filter_out(.data, ..., .by = NULL, .preserve = FALSE)## S3 method for class 'SpatRaster' filter(.data, ..., .preserve = FALSE, .keep_extent = TRUE) ## S3 method for class 'SpatVector' filter(.data, ..., .by = NULL, .preserve = FALSE) ## S3 method for class 'SpatVector' filter_out(.data, ..., .by = NULL, .preserve = FALSE)
.data |
A |
... |
< |
.preserve |
Relevant when the |
.keep_extent |
Logical. If |
.by |
< |
A Spat* object of the same class as .data. See Methods.
Implementation of the generic dplyr::filter() method.
SpatRasterCells that do not meet the conditions on ... are returned with value
NA. On a multi-layer SpatRaster the NA is propagated across all the
layers.
If .keep_extent = TRUE the returned SpatRaster has the same CRS, extent,
resolution and hence the same number of cells as .data. If
.keep_extent = FALSE the outer NA cells are trimmed with terra::trim(),
so the extent and number of cells may differ. The output will still have
the same CRS and resolution as .data.
x and y variables (i.e. the longitude and latitude of the SpatRaster)
are also available internally for filtering. See Examples.
SpatVectorThe result is a SpatVector with all the geometries that produce a value of
TRUE for all conditions.
Other single table verbs:
arrange.SpatVector(),
mutate.Spat,
reframe.SpatVector(),
rename.Spat,
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on rows:
arrange.SpatVector(),
distinct.SpatVector(),
rows.SpatVector,
slice.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) |> select(tavg_04) plot(r) # Filter temps r_f <- r |> filter(tavg_04 > 11.5) # Extent is kept plot(r_f) # Filter temps and extent r_f2 <- r |> filter(tavg_04 > 11.5, .keep_extent = FALSE) # Extent has changed plot(r_f2) # Filter by geographic coordinates r2 <- project(r, "epsg:4326") r2 |> plot() r2 |> filter( x > -4, x < -2, y > 42 ) |> plot() v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) glimpse(v) v |> filter(cpro < 10) # Same as v |> filter_out(cpro >= 10)library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) |> select(tavg_04) plot(r) # Filter temps r_f <- r |> filter(tavg_04 > 11.5) # Extent is kept plot(r_f) # Filter temps and extent r_f2 <- r |> filter(tavg_04 > 11.5, .keep_extent = FALSE) # Extent has changed plot(r_f2) # Filter by geographic coordinates r2 <- project(r, "epsg:4326") r2 |> plot() r2 |> filter( x > -4, x < -2, y > 42 ) |> plot() v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) glimpse(v) v |> filter(cpro < 10) # Same as v |> filter_out(cpro >= 10)
Spat* ObjectsFortify SpatRaster and SpatVector objects to data frames. This provides
native compatibility with ggplot2::ggplot().
Note that these methods are now implemented as a wrapper around
tidy.Spat methods.
## S3 method for class 'SpatRaster' fortify( model, data, ..., .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet"), maxcell = terra::ncell(model) * 1.1, pivot = FALSE ) ## S3 method for class 'SpatVector' fortify(model, data, ...) ## S3 method for class 'SpatGraticule' fortify(model, data, ...) ## S3 method for class 'SpatExtent' fortify(model, data, ..., crs = "")## S3 method for class 'SpatRaster' fortify( model, data, ..., .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet"), maxcell = terra::ncell(model) * 1.1, pivot = FALSE ) ## S3 method for class 'SpatVector' fortify(model, data, ...) ## S3 method for class 'SpatGraticule' fortify(model, data, ...) ## S3 method for class 'SpatExtent' fortify(model, data, ..., crs = "")
model |
A |
data |
Not used by this method. |
... |
Ignored by these methods. |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
maxcell |
Positive integer. Maximum number of cells to use for the plot. |
pivot |
Logical. When |
crs |
Input that includes or represents a CRS. It can be an |
fortify.SpatVector(), fortify.SpatGraticule() and fortify.SpatExtent()
return a sf object.
fortify.SpatRaster() returns a tibble. See Methods.
Implementation of the generic ggplot2::fortify() method.
SpatRasterReturn a tibble that can be used with ggplot2::geom_* like
ggplot2::geom_point(), ggplot2::geom_raster(), etc.
The resulting tibble includes the coordinates on the columns x, y. The
values of each layer are included as additional columns named as per the
name of the layer on the SpatRaster.
The CRS of the SpatRaster can be retrieved with
attr(fortifiedSpatRaster, "crs").
You can convert the fortified object back to a SpatRaster with
as_spatraster().
When pivot = TRUE the SpatRaster is fortified in a "long" format (see
tidyr::pivot_longer()). The fortified object has the following
columns:
x,y: Coordinates (center) of the cell on the corresponding CRS.
lyr: Indicating the name of the SpatRaster layer of value.
value: The value of the SpatRaster in the corresponding lyr.
This option may be useful when using several geom_* and for faceting, see
Examples.
SpatVector, SpatGraticule and SpatExtent
Return a sf object that can be used with ggplot2::geom_sf().
tidy.Spat, sf::st_as_sf(), as_tibble.Spat,
as_spatraster(), ggplot2::fortify().
Other ggplot2 utils:
autoplot.Spat,
geom_spat_contour,
geom_spatraster(),
geom_spatraster_rgb(),
ggspatvector,
stat_spat_coordinates()
Other ggplot2 methods:
autoplot.Spat
Coercing objects:
as_coordinates(),
as_sf(),
as_spatraster(),
as_spatvector(),
as_tibble.Spat,
tidy.Spat
# Demonstrate the use with ggplot2 library(ggplot2) # Get a SpatRaster r <- system.file("extdata/volcano2.tif", package = "tidyterra") |> terra::rast() |> terra::project("EPSG:4326") # You can now use a SpatRaster with any geom ggplot(r, maxcell = 50) + geom_histogram(aes(x = elevation), bins = 20, fill = "lightblue", color = "black" ) # For SpatVector, SpatGraticule and SpatExtent you can use now geom_sf() # Create a SpatVector extfile <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl <- terra::vect(extfile) class(cyl) ggplot(cyl) + geom_sf() # SpatGraticule g <- terra::graticule(60, 30, crs = "+proj=robin") class(g) ggplot(g) + geom_sf() # SpatExtent ex <- terra::ext(cyl) class(ex) ggplot(ex, crs = cyl) + geom_sf(fill = "red", alpha = 0.3) + geom_sf(data = cyl, fill = NA)# Demonstrate the use with ggplot2 library(ggplot2) # Get a SpatRaster r <- system.file("extdata/volcano2.tif", package = "tidyterra") |> terra::rast() |> terra::project("EPSG:4326") # You can now use a SpatRaster with any geom ggplot(r, maxcell = 50) + geom_histogram(aes(x = elevation), bins = 20, fill = "lightblue", color = "black" ) # For SpatVector, SpatGraticule and SpatExtent you can use now geom_sf() # Create a SpatVector extfile <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl <- terra::vect(extfile) class(cyl) ggplot(cyl) + geom_sf() # SpatGraticule g <- terra::graticule(60, 30, crs = "+proj=robin") class(g) ggplot(g) + geom_sf() # SpatExtent ex <- terra::ext(cyl) class(ex) ggplot(ex, crs = cyl) + geom_sf(fill = "red", alpha = 0.3) + geom_sf(data = cyl, fill = NA)
SpatRaster contoursThese geoms create contours of SpatRaster objects. To specify a valid
surface, you should specify the layer on aes(z = layer_name), otherwise all
the layers are considered for creating contours. See also Facets
section.
The underlying implementation is based on ggplot2::geom_contour().
geom_spatraster_contour_text() creates labeled contours and it is
implemented on top of isoband::isolines_grob().
geom_spatraster_contour( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE ) geom_spatraster_contour_text( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, size.unit = "mm", label_format = scales::label_number(), label_placer = isoband::label_placer_minmax(), na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE ) geom_spatraster_contour_filled( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE )geom_spatraster_contour( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE ) geom_spatraster_contour_text( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, size.unit = "mm", label_format = scales::label_number(), label_placer = isoband::label_placer_minmax(), na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE ) geom_spatraster_contour_filled( mapping = NULL, data, ..., maxcell = 5e+05, bins = NULL, binwidth = NULL, breaks = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE, mask_projection = FALSE )
mapping |
Set of aesthetic mappings created by |
data |
A |
... |
Other arguments passed on to
|
maxcell |
Positive integer. Maximum number of cells to use for the plot. |
bins |
Number of contour bins. Overridden by |
binwidth |
The width of the contour bins. Overridden by |
breaks |
One of:
Overrides |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
mask_projection |
Logical, defaults to |
size.unit |
How the |
label_format |
One of:
|
label_placer |
Function that controls how labels are placed along
the isolines. Uses |
A ggplot2 layer
geom_spatraster_contour() / geom_spatraster_contour_text() understands
the following aesthetics:
linewidth
geom_spatraster_contour_text() understands also:
label
family
fontface
Additionally, geom_spatraster_contour_filled() understands also the
following aesthetics, as well as the ones listed above:
subgroup
Check ggplot2::geom_contour() for more info on contours and
vignette("ggplot2-specs", package = "ggplot2") for an overview of the
aesthetics.
These geom computes internally some variables that are available for use as
aesthetics, using (for example) aes(color = after_stat(<computed>)) (see
ggplot2::after_stat()).
after_stat(lyr): Name of the layer.
after_stat(level): Height of contour. For contour lines, this is
a numeric vector that represents bin boundaries. For contour bands,
this is an ordered factor that represents bin ranges.
after_stat(nlevel): Height of contour, scaled to maximum of 1.
after_stat(level_low), after_stat(level_high),
after_stat(level_mid): (contour bands only) Lower and upper bin
boundaries for each band, as well the mid point between the boundaries.
z: After contouring, the z values of individual data points are no
longer available.
When the SpatRaster does not have a CRS (i.e.,
terra::crs(rast) == "") the geom does not make any assumption about the
scales.
On SpatRaster that have a CRS, the geom uses ggplot2::coord_sf() to
adjust the scales. That means that also the
SpatRaster may be reprojected.
You can use facet_wrap(~lyr) for creating a faceted plot by each layer of
the SpatRaster object. See ggplot2::facet_wrap() for details.
The metR package also provides a set of alternative functions:
metR::geom_contour2().
metR::geom_text_contour() and metR::geom_label_contour().
metR::geom_contour_tanaka().
Other ggplot2 utils:
autoplot.Spat,
fortify.Spat,
geom_spatraster(),
geom_spatraster_rgb(),
ggspatvector,
stat_spat_coordinates()
library(terra) # Raster f <- system.file("extdata/volcano2.tif", package = "tidyterra") r <- rast(f) library(ggplot2) ggplot() + geom_spatraster_contour(data = r) # Labelled ggplot() + geom_spatraster_contour_text( data = r, breaks = c(110, 130, 160, 190), color = "grey10", family = "serif" ) ggplot() + geom_spatraster_contour( data = r, aes(color = after_stat(level)), binwidth = 1, linewidth = 0.4 ) + scale_color_gradientn( colours = hcl.colors(20, "Inferno"), guide = guide_coloursteps() ) + theme_minimal() # Filled with breaks ggplot() + geom_spatraster_contour_filled(data = r, breaks = seq(80, 200, 10)) + scale_fill_hypso_d() # Both lines and contours ggplot() + geom_spatraster_contour_filled( data = r, breaks = seq(80, 200, 10), alpha = 0.7 ) + geom_spatraster_contour( data = r, breaks = seq(80, 200, 2.5), color = "grey30", linewidth = 0.1 ) + scale_fill_hypso_d()library(terra) # Raster f <- system.file("extdata/volcano2.tif", package = "tidyterra") r <- rast(f) library(ggplot2) ggplot() + geom_spatraster_contour(data = r) # Labelled ggplot() + geom_spatraster_contour_text( data = r, breaks = c(110, 130, 160, 190), color = "grey10", family = "serif" ) ggplot() + geom_spatraster_contour( data = r, aes(color = after_stat(level)), binwidth = 1, linewidth = 0.4 ) + scale_color_gradientn( colours = hcl.colors(20, "Inferno"), guide = guide_coloursteps() ) + theme_minimal() # Filled with breaks ggplot() + geom_spatraster_contour_filled(data = r, breaks = seq(80, 200, 10)) + scale_fill_hypso_d() # Both lines and contours ggplot() + geom_spatraster_contour_filled( data = r, breaks = seq(80, 200, 10), alpha = 0.7 ) + geom_spatraster_contour( data = r, breaks = seq(80, 200, 2.5), color = "grey30", linewidth = 0.1 ) + scale_fill_hypso_d()
SpatRaster objectsThis geom is used to visualise SpatRaster objects (see terra::rast()).
The geom is designed for visualise the object by layers, as terra::plot()
does.
For plotting SpatRaster objects as map tiles (i.e. RGB SpatRaster), use
geom_spatraster_rgb().
The underlying implementation is based on ggplot2::geom_raster().
stat_spatraster() complements geom_spatraster() when you need to change
the geom.
geom_spatraster( mapping = aes(), data, na.rm = TRUE, show.legend = NA, inherit.aes = FALSE, interpolate = FALSE, maxcell = 5e+05, use_coltab = TRUE, mask_projection = FALSE, ... ) stat_spatraster( mapping = aes(), data, geom = "raster", na.rm = TRUE, show.legend = NA, inherit.aes = FALSE, maxcell = 5e+05, ... )geom_spatraster( mapping = aes(), data, na.rm = TRUE, show.legend = NA, inherit.aes = FALSE, interpolate = FALSE, maxcell = 5e+05, use_coltab = TRUE, mask_projection = FALSE, ... ) stat_spatraster( mapping = aes(), data, geom = "raster", na.rm = TRUE, show.legend = NA, inherit.aes = FALSE, maxcell = 5e+05, ... )
mapping |
Set of aesthetic mappings created by |
data |
A |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
interpolate |
If |
maxcell |
Positive integer. Maximum number of cells to use for the plot. |
use_coltab |
Logical. Only applicable to |
mask_projection |
Logical, defaults to |
... |
Other arguments passed on to
|
geom |
Geom used to display the data. Recommended values for
|
A ggplot2 layer
When the SpatRaster does not have a CRS (i.e.,
terra::crs(rast) == "") the geom does not make any assumption about the
scales.
On SpatRaster that have a CRS, the geom uses ggplot2::coord_sf() to
adjust the scales. That means that also the
SpatRaster may be reprojected.
geom_spatraster() understands the following aesthetics:
If fill is not provided, geom_spatraster() creates a
ggplot2 layer with all the layers of the SpatRaster
object. Use facet_wrap(~lyr) to properly display the SpatRaster
layers.
If fill is used, it should contain the name of one layer that is present
on the SpatRaster (i.e.
geom_spatraster(data = rast, aes(fill = <name_of_lyr>)). Names of the
layers can be retrieved using names(rast).
Using geom_spatraster(..., mapping = aes(fill = NULL)) or
geom_spatraster(..., fill = <color value(s)>) creates a layer with no
mapped fill aesthetic.
fill can use computed variables.
For alpha use computed variable. See section Computed variables.
stat_spatraster()stat_spatraster() understands the same aesthetics as geom_spatraster()
when geom = "raster" (the default):
When geom = "raster", the fill argument behaves as in
geom_spatraster(). If another geom is used, stat_spatraster()
understands the aesthetics required by that geom, so
aes(fill = <name_of_lyr>) is not applicable.
The x and y aesthetics are mapped by default, so you do not need to add
them in aes(). In every case, aesthetics should be mapped with computed
variables. See Computed variables and Examples.
You can use facet_wrap(~lyr) for creating a faceted plot by each layer of
the SpatRaster object. See ggplot2::facet_wrap() for details.
This geom computes internally some variables that are available for use as
aesthetics, using (for example) aes(alpha = after_stat(value)) (see
ggplot2::after_stat()).
after_stat(value): Values of the SpatRaster.
after_stat(lyr): Name of the layer.
Based on the layer_spatial() implementation on ggspatial package.
Thanks to Dewey Dunnington and ggspatial contributors.
ggplot2::geom_raster(), ggplot2::coord_sf(),
ggplot2::facet_wrap()
Recommended geoms:
Other ggplot2 utils:
autoplot.Spat,
fortify.Spat,
geom_spat_contour,
geom_spatraster_rgb(),
ggspatvector,
stat_spat_coordinates()
# Avg temperature on spring in Castile and Leon (Spain) file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) temp_rast <- rast(file_path) library(ggplot2) # Display a single layer names(temp_rast) ggplot() + geom_spatraster(data = temp_rast, aes(fill = tavg_04)) + # You can use coord_sf coord_sf(crs = 3857) + scale_fill_grass_c(palette = "celsius") # Display facets ggplot() + geom_spatraster(data = temp_rast) + facet_wrap(~lyr, ncol = 2) + scale_fill_grass_b(palette = "celsius", breaks = seq(0, 20, 2.5)) # Non spatial rasters no_crs <- rast(crs = NA, extent = c(0, 100, 0, 100), nlyr = 1) values(no_crs) <- seq_len(ncell(no_crs)) ggplot() + geom_spatraster(data = no_crs) # Downsample ggplot() + geom_spatraster(data = no_crs, maxcell = 25) # Using stat_spatraster # Default ggplot() + stat_spatraster(data = temp_rast) + facet_wrap(~lyr) # Using points ggplot() + stat_spatraster( data = temp_rast, aes(color = after_stat(value)), geom = "point", maxcell = 250 ) + scale_colour_viridis_c(na.value = "transparent") + facet_wrap(~lyr) # Using points and labels r_single <- temp_rast |> select(1) ggplot() + stat_spatraster( data = r_single, aes(color = after_stat(value)), geom = "point", maxcell = 2000 ) + stat_spatraster( data = r_single, aes(label = after_stat(round(value, 2))), geom = "label", alpha = 0.85, maxcell = 20 ) + scale_colour_viridis_c(na.value = "transparent")# Avg temperature on spring in Castile and Leon (Spain) file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) temp_rast <- rast(file_path) library(ggplot2) # Display a single layer names(temp_rast) ggplot() + geom_spatraster(data = temp_rast, aes(fill = tavg_04)) + # You can use coord_sf coord_sf(crs = 3857) + scale_fill_grass_c(palette = "celsius") # Display facets ggplot() + geom_spatraster(data = temp_rast) + facet_wrap(~lyr, ncol = 2) + scale_fill_grass_b(palette = "celsius", breaks = seq(0, 20, 2.5)) # Non spatial rasters no_crs <- rast(crs = NA, extent = c(0, 100, 0, 100), nlyr = 1) values(no_crs) <- seq_len(ncell(no_crs)) ggplot() + geom_spatraster(data = no_crs) # Downsample ggplot() + geom_spatraster(data = no_crs, maxcell = 25) # Using stat_spatraster # Default ggplot() + stat_spatraster(data = temp_rast) + facet_wrap(~lyr) # Using points ggplot() + stat_spatraster( data = temp_rast, aes(color = after_stat(value)), geom = "point", maxcell = 250 ) + scale_colour_viridis_c(na.value = "transparent") + facet_wrap(~lyr) # Using points and labels r_single <- temp_rast |> select(1) ggplot() + stat_spatraster( data = r_single, aes(color = after_stat(value)), geom = "point", maxcell = 2000 ) + stat_spatraster( data = r_single, aes(label = after_stat(round(value, 2))), geom = "label", alpha = 0.85, maxcell = 20 ) + scale_colour_viridis_c(na.value = "transparent")
SpatRaster objects as imagesThis geom is used to visualise SpatRaster objects (see terra::rast()) as
RGB images. The layers are combined so they represent the red, green and
blue channels.
For plotting SpatRaster objects by layer values use geom_spatraster().
The underlying implementation is based on ggplot2::geom_raster().
geom_spatraster_rgb( mapping = aes(), data, interpolate = TRUE, r = 1, g = 2, b = 3, alpha = 1, maxcell = 5e+05, max_col_value = 255, ..., stretch = NULL, zlim = NULL, mask_projection = FALSE )geom_spatraster_rgb( mapping = aes(), data, interpolate = TRUE, r = 1, g = 2, b = 3, alpha = 1, maxcell = 5e+05, max_col_value = 255, ..., stretch = NULL, zlim = NULL, mask_projection = FALSE )
mapping |
Ignored. |
data |
A |
interpolate |
If |
r, g, b
|
Integer giving the layer number in |
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
maxcell |
Positive integer. Maximum number of cells to use for the plot. |
max_col_value |
Number giving the upper bound of the color value range.
When this is |
... |
Other arguments passed on to
|
stretch |
character. Option to stretch the values to increase contrast: "lin" (linear) or "hist" (histogram). The linear stretch uses |
zlim |
numeric vector of length 2. Range of values to plot (optional). If this is set, and |
mask_projection |
Logical, defaults to |
A ggplot2 layer
No aes() is required. In fact, aes() will be ignored.
When the SpatRaster does not have a CRS (i.e.,
terra::crs(rast) == "") the geom does not make any assumption about the
scales.
On SpatRaster that have a CRS, the geom uses ggplot2::coord_sf() to
adjust the scales. That means that also the
SpatRaster may be reprojected.
Based on the layer_spatial() implementation in the ggspatial
package. Thanks to Dewey Dunnington and to
ggspatial contributors.
ggplot2::geom_raster(), ggplot2::coord_sf(), grDevices::rgb().
You can also get RGB tiles from the maptiles package. See
maptiles::get_tiles().
Other ggplot2 utils:
autoplot.Spat,
fortify.Spat,
geom_spat_contour,
geom_spatraster(),
ggspatvector,
stat_spat_coordinates()
# Tile of Castile and Leon (Spain) from OpenStreetMap file_path <- system.file("extdata/cyl_tile.tif", package = "tidyterra") library(terra) tile <- rast(file_path) library(ggplot2) ggplot() + geom_spatraster_rgb(data = tile) + # You can use coord_sf coord_sf(crs = 3035) # Combine with sf objects vect_path <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl_sf <- sf::st_read(vect_path) ggplot(cyl_sf) + geom_spatraster_rgb(data = tile) + geom_sf(aes(fill = iso2)) + coord_sf(crs = 3857) + scale_fill_viridis_d(alpha = 0.7)# Tile of Castile and Leon (Spain) from OpenStreetMap file_path <- system.file("extdata/cyl_tile.tif", package = "tidyterra") library(terra) tile <- rast(file_path) library(ggplot2) ggplot() + geom_spatraster_rgb(data = tile) + # You can use coord_sf coord_sf(crs = 3035) # Combine with sf objects vect_path <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl_sf <- sf::st_read(vect_path) ggplot(cyl_sf) + geom_spatraster_rgb(data = tile) + geom_sf(aes(fill = iso2)) + coord_sf(crs = 3857) + scale_fill_viridis_d(alpha = 0.7)
SpatVector objectsWrappers of ggplot2::geom_sf() family used to visualise SpatVector
objects (see terra::vect()).
geom_spatvector( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ... ) geom_spatvector_label( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ..., linewidth = 0.25, inherit.aes = TRUE ) geom_spatvector_text( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ..., check_overlap = FALSE, inherit.aes = TRUE ) stat_spatvector( mapping = NULL, data = NULL, geom = "rect", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )geom_spatvector( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ... ) geom_spatvector_label( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ..., linewidth = 0.25, inherit.aes = TRUE ) geom_spatvector_text( mapping = aes(), data = NULL, na.rm = FALSE, show.legend = NA, ..., check_overlap = FALSE, inherit.aes = TRUE ) stat_spatvector( mapping = NULL, data = NULL, geom = "rect", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
A |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
You can also set this to one of "polygon", "line", and "point" to override the default legend. |
... |
Other arguments passed on to |
linewidth |
Size of label border, in mm. |
inherit.aes |
If |
check_overlap |
If |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
These functions are wrappers of ggplot2::geom_sf() functions. Since a
fortify.SpatVector() method is provided, ggplot2 treat a
SpatVector in the same way that a sf object. A side effect
is that you can use ggplot2::geom_sf() directly with SpatVector objects.
See ggplot2::geom_sf() for details on aesthetics, etc.
A ggplot2 layer
Other ggplot2 utils:
autoplot.Spat,
fortify.Spat,
geom_spat_contour,
geom_spatraster(),
geom_spatraster_rgb(),
stat_spat_coordinates()
# Create a SpatVector extfile <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl <- terra::vect(extfile) class(cyl) library(ggplot2) ggplot(cyl) + geom_spatvector() # With params ggplot(cyl) + geom_spatvector(aes(fill = name), color = NA) + scale_fill_viridis_d() + coord_sf(crs = 3857) # Add labels ggplot(cyl) + geom_spatvector(aes(fill = name), color = NA) + geom_spatvector_text(aes(label = iso2), fontface = "bold", color = "red" ) + scale_fill_viridis_d(alpha = 0.4) + coord_sf(crs = 3857) # You can use now geom_sf with SpatVectors! ggplot(cyl) + geom_sf() + labs( title = paste("cyl is", as.character(class(cyl))), subtitle = "With geom_sf()" )# Create a SpatVector extfile <- system.file("extdata/cyl.gpkg", package = "tidyterra") cyl <- terra::vect(extfile) class(cyl) library(ggplot2) ggplot(cyl) + geom_spatvector() # With params ggplot(cyl) + geom_spatvector(aes(fill = name), color = NA) + scale_fill_viridis_d() + coord_sf(crs = 3857) # Add labels ggplot(cyl) + geom_spatvector(aes(fill = name), color = NA) + geom_spatvector_text(aes(label = iso2), fontface = "bold", color = "red" ) + scale_fill_viridis_d(alpha = 0.4) + coord_sf(crs = 3857) # You can use now geom_sf with SpatVectors! ggplot(cyl) + geom_sf() + labs( title = paste("cyl is", as.character(class(cyl))), subtitle = "With geom_sf()" )
Spat* objectGlance accepts a model object and returns a tibble::tibble() with exactly
one row of Spat. The summaries are typically geographic information.
## S3 method for class 'SpatRaster' glance(x, ...) ## S3 method for class 'SpatVector' glance(x, ...)## S3 method for class 'SpatRaster' glance(x, ...) ## S3 method for class 'SpatVector' glance(x, ...)
x |
A |
... |
Ignored by this method. |
glance methods always return a one-row data frame. See Methods.
Implementation of the generic generics::glance() method for
Spat*. objects.
glimpse.Spat, generics::glance().
Other generics methods:
required_pkgs.Spat,
tidy.Spat
library(terra) # SpatVector v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) glance(v) # SpatRaster r <- rast(system.file("extdata/cyl_elev.tif", package = "tidyterra")) glance(r)library(terra) # SpatVector v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) glance(v) # SpatRaster r <- rast(system.file("extdata/cyl_elev.tif", package = "tidyterra")) glance(r)
Spat* objectsglimpse() is like a transposed version of print(): layers/columns run
down the page and data runs across. This makes it possible to see every
layer/column in a Spat* object.
## S3 method for class 'SpatRaster' glimpse(x, width = NULL, ..., n = 10, max_extra_cols = 20) ## S3 method for class 'SpatVector' glimpse(x, width = NULL, ..., n = 10, max_extra_cols = 20)## S3 method for class 'SpatRaster' glimpse(x, width = NULL, ..., n = 10, max_extra_cols = 20) ## S3 method for class 'SpatVector' glimpse(x, width = NULL, ..., n = 10, max_extra_cols = 20)
x |
A |
width |
Width of output: defaults to the setting of the
|
... |
Arguments passed on to |
n |
Maximum number of rows to show. |
max_extra_cols |
Number of extra columns or layers to print abbreviated
information for, if |
original x is (invisibly) returned, allowing glimpse() to
be used within a data pipeline.
print()
Implementation of the generic dplyr::glimpse() function for
Spat*. objects.
Other dplyr verbs that operate on columns:
mutate.Spat,
pull.Spat,
relocate.Spat,
rename.Spat,
select.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) # SpatVector v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v |> glimpse(n = 2) # Use on a pipeline v |> glimpse() |> mutate(a = 30) |> # with options glimpse(geom = "WKT") # SpatRaster r <- rast(system.file("extdata/cyl_elev.tif", package = "tidyterra")) r |> glimpse() # Use on a pipeline r |> glimpse() |> mutate(b = elevation_m / 100) |> # With options glimpse(xy = TRUE)library(terra) # SpatVector v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v |> glimpse(n = 2) # Use on a pipeline v |> glimpse() |> mutate(a = 30) |> # with options glimpse(geom = "WKT") # SpatRaster r <- rast(system.file("extdata/cyl_elev.tif", package = "tidyterra")) r |> glimpse() # Use on a pipeline r |> glimpse() |> mutate(b = elevation_m / 100) |> # With options glimpse(xy = TRUE)
A tibble including the color map of
51 gradient palettes. Some palettes also
include a definition of color limits that can be used with
ggplot2::scale_fill_gradientn().
A tibble of 2920 rows and 6 columns with the following fields:
Name of the palette.
(Optional) limit for each color.
Value of the red channel (RGB color mode).
Value of the green channel (RGB color mode).
Value of the blue channel (RGB color mode).
Hex code of the color.
Summary of palettes provided, description and recommended use:
| palette | use | description | range |
aspect |
General | aspect oriented grey colors | |
aspectcolr |
General | aspect oriented rainbow colors | 0 to 360 |
bcyr |
General | blue through cyan through yellow to red | |
bgyr |
General | blue through green through yellow to red | |
blues |
General | white to blue | |
byg |
General | blue through yellow to green | |
byr |
General | blue through yellow to red | |
celsius |
General | blue to red for degree Celsius temperature | -80 to 80 |
corine |
Land Cover | EU Corine land cover colors | 111 to 995 |
curvature |
General | for terrain curvatures | -0.1 to 0.1 |
differences |
General | differences oriented colors | |
elevation |
Topography | maps relative ranges of raster values to elevation color ramp | |
etopo2 |
Topography | colors for ETOPO2 worldwide bathymetry/topography | -11000 to 8850 |
evi |
Natural | enhanced vegetative index colors | -1 to 1 |
fahrenheit |
Temperature | blue to red for Fahrenheit temperature | -112 to 176 |
forest_cover |
Natural | percentage of forest cover | 0 to 1 |
gdd |
Natural | accumulated growing degree days | 0 to 6000 |
grass |
General | GRASS GIS green (perceptually uniform) | |
greens |
General | white to green | |
grey |
General | grey scale | |
gyr |
General | green through yellow to red | |
haxby |
Topography | relative colors for bathymetry or topography | |
inferno |
General | perceptually uniform sequential color table inferno | |
kelvin |
Temperature | blue to red for temperature in Kelvin scale | 193.15 to 353.15 |
magma |
General | perceptually uniform sequential color table magma | |
ndvi |
Natural | Normalized Difference Vegetation Index colors | -1 to 1 |
ndwi |
Natural | Normalized Difference Water Index colors | -200 to 200 |
nlcd |
Land Cover | US National Land Cover Dataset colors | 0 to 95 |
oranges |
General | white to orange | |
plasma |
General | perceptually uniform sequential color table plasma | |
population |
Human | color table covering human population classification breaks | 0 to 1000000 |
population_dens |
Human | color table covering human population density classification breaks | 0 to 1000 |
precipitation |
Climate | precipitation color table (0..2000mm) | 0 to 7000 |
precipitation_daily |
Climate | precipitation color table (0..1000mm) | 0 to 100 |
precipitation_monthly |
Climate | precipitation color table (0..1000mm) | 0 to 1000 |
rainbow |
General | rainbow color table | |
ramp |
General | color ramp | |
reds |
General | white to red | |
roygbiv |
General | ||
rstcurv |
General | terrain curvature (from r.resamp.rst) | -0.1 to 0.1 |
ryb |
General | red through yellow to blue | |
ryg |
General | red through yellow to green | |
sepia |
General | yellowish-brown through to white | |
slope |
General | r.slope.aspect-type slope colors for raster values 0-90 | 0 to 90 |
soilmoisture |
Natural | soil moisture color table (0.0-1.0) | 0 to 1 |
srtm |
Topography | color palette for Shuttle Radar Topography Mission elevation | -11000 to 8850 |
srtm_plus |
Topography | color palette for Shuttle Radar Topography Mission elevation (with seafloor colors) | -11000 to 8850 |
terrain |
Topography | global elevation color table covering -11000 to +8850m | -11000 to 8850 |
viridis |
General | perceptually uniform sequential color table viridis | |
water |
Natural | water depth | |
wave |
General | color wave |
Derived from https://github.com/OSGeo/grass/tree/main/lib/gis/colors. See also r.color - GRASS GIS Manual.
GRASS Development Team (2024). Geographic Resources Analysis Support System (GRASS) Software, Version 8.3.2. Open Source Geospatial Foundation, USA. https://grass.osgeo.org.
Other datasets:
cross_blended_hypsometric_tints_db,
hypsometric_tints_db,
princess_db,
volcano2
data("grass_db") grass_db # Select a palette srtm_plus <- grass_db |> filter(pal == "srtm_plus") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = srtm_plus$hex) # Use with limits p + scale_fill_gradientn( colors = srtm_plus$hex, values = scales::rescale(srtm_plus$limit), limit = range(srtm_plus$limit), na.value = "lightblue" )data("grass_db") grass_db # Select a palette srtm_plus <- grass_db |> filter(pal == "srtm_plus") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = srtm_plus$hex) # Use with limits p + scale_fill_gradientn( colors = srtm_plus$hex, values = scales::rescale(srtm_plus$limit), limit = range(srtm_plus$limit), na.value = "lightblue" )
SpatVector by one or more variablesMost data operations are done on groups defined by variables.
group_by.SpatVector() adds new attributes to an existing SpatVector
indicating the corresponding groups. See Methods.
## S3 method for class 'SpatVector' group_by(.data, ..., .add = FALSE, .drop = group_by_drop_default(.data)) ## S3 method for class 'SpatVector' ungroup(x, ...)## S3 method for class 'SpatVector' group_by(.data, ..., .add = FALSE, .drop = group_by_drop_default(.data)) ## S3 method for class 'SpatVector' ungroup(x, ...)
.data, x
|
A |
... |
< |
.add |
When |
.drop |
Drop groups formed by factor levels that don't appear in the
data? The default is |
See Details on dplyr::group_by().
A SpatVector object with updated grouping metadata.
Implementation of the generic dplyr::group_by() family functions for
SpatVector objects.
When mixing terra and dplyr syntax
on a grouped SpatVector (i.e. subsetting a SpatVector like
v[1:3,1:2]), the groups attribute can be corrupted.
tidyterra tries to re-group the SpatVector. This is triggered
the next time you use a dplyr verb on your SpatVector.
Note also that some operations, such as terra::spatSample(), create a new
SpatVector. In these cases, the result does not preserve the groups
attribute. Use group_by() to re-group.
dplyr::group_by(), dplyr::ungroup()
Other dplyr verbs that operate on group of rows:
count.SpatVector(),
reframe.SpatVector(),
rowwise.SpatVector(),
summarise.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr grouping methods:
group_map.SpatVector(),
group_nest.SpatVector(),
group_split.SpatVector(),
group_trim.SpatVector()
library(terra) f <- system.file("ex/lux.shp", package = "terra") p <- vect(f) by_name1 <- p |> group_by(NAME_1) # Grouping does not change how the SpatVector looks. by_name1 # But it adds metadata for grouping. See the coercion to tibble. # Not grouped p_tbl <- as_tibble(p) class(p_tbl) head(p_tbl, 3) # Grouped by_name1_tbl <- as_tibble(by_name1) class(by_name1_tbl) head(by_name1_tbl, 3) # It changes how it acts with the other dplyr verbs: by_name1 |> summarise( pop = mean(POP), area = sum(AREA) ) # Each call to summarise() removes a layer of grouping by_name2_name1 <- p |> group_by(NAME_2, NAME_1) by_name2_name1 group_data(by_name2_name1) by_name2 <- by_name2_name1 |> summarise(n = dplyr::n()) by_name2 group_data(by_name2) # To removing grouping, use ungroup by_name2 |> ungroup() |> summarise(n = sum(n)) # By default, group_by() overrides existing grouping by_name2_name1 |> group_by(ID_1, ID_2) |> group_vars() # Use add = TRUE to instead append by_name2_name1 |> group_by(ID_1, ID_2, .add = TRUE) |> group_vars() # You can group by expressions: this is a short-hand # for a mutate() followed by a group_by() p |> group_by(ID_COMB = ID_1 * 100 / ID_2) |> relocate(ID_COMB, .before = 1)library(terra) f <- system.file("ex/lux.shp", package = "terra") p <- vect(f) by_name1 <- p |> group_by(NAME_1) # Grouping does not change how the SpatVector looks. by_name1 # But it adds metadata for grouping. See the coercion to tibble. # Not grouped p_tbl <- as_tibble(p) class(p_tbl) head(p_tbl, 3) # Grouped by_name1_tbl <- as_tibble(by_name1) class(by_name1_tbl) head(by_name1_tbl, 3) # It changes how it acts with the other dplyr verbs: by_name1 |> summarise( pop = mean(POP), area = sum(AREA) ) # Each call to summarise() removes a layer of grouping by_name2_name1 <- p |> group_by(NAME_2, NAME_1) by_name2_name1 group_data(by_name2_name1) by_name2 <- by_name2_name1 |> summarise(n = dplyr::n()) by_name2 group_data(by_name2) # To removing grouping, use ungroup by_name2 |> ungroup() |> summarise(n = sum(n)) # By default, group_by() overrides existing grouping by_name2_name1 |> group_by(ID_1, ID_2) |> group_vars() # Use add = TRUE to instead append by_name2_name1 |> group_by(ID_1, ID_2, .add = TRUE) |> group_vars() # You can group by expressions: this is a short-hand # for a mutate() followed by a group_by() p |> group_by(ID_COMB = ID_1 * 100 / ID_2) |> relocate(ID_COMB, .before = 1)
A tibble including the color map of
33 gradient palettes. All the
palettes. It also includes a definition of color limits in terms of
elevation (meters) that can be used with ggplot2::scale_fill_gradientn().
A tibble of 1102 rows and 6 columns with the following fields:
Name of the palette.
Recommended elevation limit (in meters) for each color.
Value of the red channel (RGB color mode).
Value of the green channel (RGB color mode).
Value of the blue channel (RGB color mode).
Hex code of the color.
cpt-city: https://phillips.shef.ac.uk/pub/cpt-city/.
Other datasets:
cross_blended_hypsometric_tints_db,
grass_db,
princess_db,
volcano2
data("hypsometric_tints_db") hypsometric_tints_db # Select a palette wikicols <- hypsometric_tints_db |> filter(pal == "wiki-2.0") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = wikicols$hex) # Use with limits p + scale_fill_gradientn( colors = wikicols$hex, values = scales::rescale(wikicols$limit), limit = range(wikicols$limit) )data("hypsometric_tints_db") hypsometric_tints_db # Select a palette wikicols <- hypsometric_tints_db |> filter(pal == "wiki-2.0") f <- system.file("extdata/asia.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = wikicols$hex) # Use with limits p + scale_fill_gradientn( colors = wikicols$hex, values = scales::rescale(wikicols$limit), limit = range(wikicols$limit) )
Assess if the coordinates x,y of an object conforms a regular grid. This function is called by its side effects.
This function is internally called by as_spatraster().
is_regular_grid(xy, digits = 6)is_regular_grid(xy, digits = 6)
xy |
A matrix, data frame or tibble of at least two columns representing x and y coordinates. |
digits |
Integer to set the precision for detecting whether points are on a regular grid (a low number of digits is a low precision). |
invisible() if is regular or an error message otherwise
Other helpers:
compare_spatrasters(),
is_grouped_spatvector(),
pull_crs()
p <- matrix(1:90, nrow = 45, ncol = 2) is_regular_grid(p) # Jitter location set.seed(1234) jitter <- runif(length(p)) / 10e4 p_jitter <- p + jitter # Need to adjust digits is_regular_grid(p_jitter, digits = 4)p <- matrix(1:90, nrow = 45, ncol = 2) is_regular_grid(p) # Jitter location set.seed(1234) jitter <- runif(length(p)) / 10e4 p_jitter <- p + jitter # Need to adjust digits is_regular_grid(p_jitter, digits = 4)
SpatVector objectsMutating joins add columns from y to x, matching observations based on
the keys. The four mutating joins are: inner join, left join, right join and
full join.
See dplyr::inner_join() for details.
## S3 method for class 'SpatVector' inner_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' left_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' right_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' full_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL )## S3 method for class 'SpatVector' inner_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' left_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' right_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL ) ## S3 method for class 'SpatVector' full_join( x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ..., keep = NULL )
x |
A |
y |
A data frame or other object coercible to a data frame. If a
|
by |
A join specification created with If To join on different variables between To join by multiple variables, use a
For simple equality joins, you can alternatively specify a character vector
of variable names to join by. For example, To perform a cross-join, generating all combinations of |
copy |
If |
suffix |
If there are non-joined duplicate variables in |
... |
Other parameters passed onto methods. |
keep |
Should the join keys from both
|
A SpatVector object.
Implementation of the generic dplyr::inner_join() family
SpatVectorThe geometry column has sticky behavior. This means that the result always
has the geometry of x for the records that match the join conditions.
For right_join() and full_join(), empty geometries may be returned
(since y is expected to be a data frame with no
geometries). Although these join operations are not common in spatial
workflows, the function may crash because handling of EMPTY
geometries differs between terra and sf.
dplyr::inner_join(), dplyr::left_join(), dplyr::right_join(),
dplyr::full_join(), terra::merge()
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
bind_rows.SpatVector,
cross_join.SpatVector(),
filter-joins.SpatVector,
nest_join.SpatVector(),
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) library(ggplot2) # Vector v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # A data frame df <- data.frame( cpro = sprintf("%02d", 1:10), x = runif(10), y = runif(10), letter = rep_len(LETTERS[1:3], length.out = 10) ) # Inner join inner <- v |> inner_join(df) nrow(inner) autoplot(inner, aes(fill = letter)) + labs(title = "Inner Join") # Left join left <- v |> left_join(df) nrow(left) autoplot(left, aes(fill = letter)) + labs(title = "Left Join") # Right join right <- v |> right_join(df) nrow(right) autoplot(right, aes(fill = letter)) + labs(title = "Right Join") # There are empty geometries, check with data from df ggplot(right, aes(x, y)) + geom_point(aes(color = letter)) # Full join full <- v |> full_join(df) nrow(full) autoplot(full, aes(fill = letter)) + labs(title = "Full Join") # Check with data from df ggplot(full, aes(x, y)) + geom_point(aes(color = letter))library(terra) library(ggplot2) # Vector v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # A data frame df <- data.frame( cpro = sprintf("%02d", 1:10), x = runif(10), y = runif(10), letter = rep_len(LETTERS[1:3], length.out = 10) ) # Inner join inner <- v |> inner_join(df) nrow(inner) autoplot(inner, aes(fill = letter)) + labs(title = "Inner Join") # Left join left <- v |> left_join(df) nrow(left) autoplot(left, aes(fill = letter)) + labs(title = "Left Join") # Right join right <- v |> right_join(df) nrow(right) autoplot(right, aes(fill = letter)) + labs(title = "Right Join") # There are empty geometries, check with data from df ggplot(right, aes(x, y)) + geom_point(aes(color = letter)) # Full join full <- v |> full_join(df) nrow(full) autoplot(full, aes(fill = letter)) + labs(title = "Full Join") # Check with data from df ggplot(full, aes(x, y)) + geom_point(aes(color = letter))
Spat* objectsmutate() adds new layers/attributes and preserves existing ones on a
Spat* object.
## S3 method for class 'SpatRaster' mutate( .data, ..., .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL ) ## S3 method for class 'SpatVector' mutate( .data, ..., .by = NULL, .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL )## S3 method for class 'SpatRaster' mutate( .data, ..., .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL ) ## S3 method for class 'SpatVector' mutate( .data, ..., .by = NULL, .keep = c("all", "used", "unused", "none"), .before = NULL, .after = NULL )
.data |
A |
... |
< The value can be:
|
.keep |
Control which columns from
|
.before, .after
|
< |
.by |
< |
A Spat* object of the same class as .data. See Methods.
Some terra methods for modifying cell values:
terra::ifel(), terra::classify(), terra::clamp(), terra::app(),
terra::lapp(), terra::tapp()
Implementation of the generic dplyr::mutate() method.
SpatRasterAdd new layers and preserves existing ones. The result is a
SpatRaster with the same extent, resolution and CRS as .data. Only the
values (and possibly the number) of layers is modified.
SpatVectorThe result is a SpatVector with the modified (and possibly renamed)
attributes on the function call.
dplyr::mutate() methods.
terra provides several ways to modify Spat* objects:
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
reframe.SpatVector(),
rename.Spat,
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on columns:
glimpse.Spat,
pull.Spat,
relocate.Spat,
rename.Spat,
select.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) # SpatRaster method f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") spatrast <- rast(f) mod <- spatrast |> mutate(exp_lyr1 = exp(tavg_04 / 10)) |> select(tavg_04, exp_lyr1) mod plot(mod) # SpatVector method f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) v |> mutate(cpro2 = paste0(cpro, "-CyL")) |> select(cpro, cpro2)library(terra) # SpatRaster method f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") spatrast <- rast(f) mod <- spatrast |> mutate(exp_lyr1 = exp(tavg_04 / 10)) |> select(tavg_04, exp_lyr1) mod plot(mod) # SpatVector method f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) v |> mutate(cpro2 = paste0(cpro, "-CyL")) |> select(cpro, cpro2)
SpatVector objectsnest_join() returns a tibble with the attributes and geometry of x, plus
a list-column containing matching rows from y.
## S3 method for class 'SpatVector' nest_join( x, y, by = NULL, copy = FALSE, keep = NULL, name = NULL, ..., na_matches = c("na", "never") )## S3 method for class 'SpatVector' nest_join( x, y, by = NULL, copy = FALSE, keep = NULL, name = NULL, ..., na_matches = c("na", "never") )
x |
A |
y |
A data frame. Spatial |
by |
A join specification created with If To join on different variables between To join by multiple variables, use a
For simple equality joins, you can alternatively specify a character vector
of variable names to join by. For example, To perform a cross-join, generating all combinations of |
copy |
If |
keep |
Should the new list-column contain join keys? The default will preserve the join keys for inequality joins. |
name |
The name of the list-column created by the join. If |
... |
Other parameters passed onto methods. |
na_matches |
Should two |
A tibble.
Implementation of the generic dplyr::nest_join() method.
SpatVectorThe output is a tibble with the attributes and WKT geometry of x, plus a
list-column with matching rows from y.
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
bind_rows.SpatVector,
cross_join.SpatVector(),
filter-joins.SpatVector,
mutate-joins.SpatVector,
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) extra <- tibble::tibble(cpro = c("05", "09"), value = c(1, 2)) nest_join(v, extra, by = "cpro")v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) extra <- tibble::tibble(cpro = c("05", "09"), value = c(1, 2)) nest_join(v, extra, by = "cpro")
SpatVector rowsnest() creates list-columns of SpatVector objects.
## S3 method for class 'SpatVector' nest(.data, ..., .by = NULL, .key = NULL, .names_sep = NULL)## S3 method for class 'SpatVector' nest(.data, ..., .by = NULL, .key = NULL, .names_sep = NULL)
.data |
A |
... |
< Specified using name-variable pairs of the form
If not supplied, then
|
.by |
<
If not supplied, then |
.key |
The name of the resulting nested column. Only applicable when
If |
.names_sep |
If |
A tibble with one or more list-columns of SpatVector objects.
Implementation of the generic tidyr::nest() method.
SpatVectorThe geometry column must be nested with the other attributes that form each
nested SpatVector. These nested list-columns contain SpatVector objects
and cannot be passed directly to tidyr::unnest().
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v |> group_by(cpro) |> nest() # Convert to a named SpatVectorCollection. nested <- nest(v, .by = cpro) sv <- pull(nested, data) names(sv) <- pull(nested, cpro) terra::svc(sv)v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v |> group_by(cpro) |> nest() # Convert to a named SpatVectorCollection. nested <- nest(v, .by = cpro) sv <- pull(nested, data) names(sv) <- pull(nested, cpro) terra::svc(sv)
SpatVector from wide to longpivot_longer() "lengthens" data, increasing the number of rows and
decreasing the number of columns. The inverse transformation is
pivot_wider.SpatVector()
Learn more in tidyr::pivot_longer().
## S3 method for class 'SpatVector' pivot_longer( data, cols, ..., cols_vary = "fastest", names_to = "name", names_prefix = NULL, names_sep = NULL, names_pattern = NULL, names_ptypes = NULL, names_transform = NULL, names_repair = "check_unique", values_to = "value", values_drop_na = FALSE, values_ptypes = NULL, values_transform = NULL )## S3 method for class 'SpatVector' pivot_longer( data, cols, ..., cols_vary = "fastest", names_to = "name", names_prefix = NULL, names_sep = NULL, names_pattern = NULL, names_ptypes = NULL, names_transform = NULL, names_repair = "check_unique", values_to = "value", values_drop_na = FALSE, values_ptypes = NULL, values_transform = NULL )
data |
A |
cols |
< |
... |
Additional arguments passed on to methods. |
cols_vary |
When pivoting
|
names_to |
A character vector specifying the new column or columns to
create from the information stored in the column names of
|
names_prefix |
A regular expression used to remove matching text from the start of each variable name. |
names_sep, names_pattern
|
If
If these arguments do not give you enough control, use
|
names_ptypes, values_ptypes
|
Optionally, a list of column name-prototype
pairs. Alternatively, a single empty prototype can be supplied, which will
be applied to all columns. A prototype (or ptype for short) is a
zero-length vector (like |
names_transform, values_transform
|
Optionally, a list of column
name-function pairs. Alternatively, a single function can be supplied,
which will be applied to all columns. Use these arguments if you need to
change the types of specific columns. For example, If not specified, the type of the columns generated from |
names_repair |
What happens if the output has invalid column names?
The default, |
values_to |
A string specifying the name of the column to create
from the data stored in cell values. If |
values_drop_na |
If |
A SpatVector object.
Implementation of the generic tidyr::pivot_longer() method.
SpatVectorThe geometry column has sticky behavior. This means that the result always
has the geometry of data.
Other tidyr verbs for pivoting:
pivot_wider.SpatVector()
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
library(dplyr) library(tidyr) library(ggplot2) library(terra) temp <- rast((system.file("extdata/cyl_temp.tif", package = "tidyterra"))) cyl <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) |> project(temp) # Add average temp temps <- terra::extract(temp, cyl, fun = "mean", na.rm = TRUE, xy = TRUE) cyl_temp <- cbind(cyl, temps) |> glimpse() # And pivot long for plot cyl_temp |> pivot_longer( cols = tavg_04:tavg_06, names_to = "label", values_to = "temp" ) |> ggplot() + geom_spatvector(aes(fill = temp)) + facet_wrap(~label, ncol = 1) + scale_fill_whitebox_c(palette = "muted")library(dplyr) library(tidyr) library(ggplot2) library(terra) temp <- rast((system.file("extdata/cyl_temp.tif", package = "tidyterra"))) cyl <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) |> project(temp) # Add average temp temps <- terra::extract(temp, cyl, fun = "mean", na.rm = TRUE, xy = TRUE) cyl_temp <- cbind(cyl, temps) |> glimpse() # And pivot long for plot cyl_temp |> pivot_longer( cols = tavg_04:tavg_06, names_to = "label", values_to = "temp" ) |> ggplot() + geom_spatvector(aes(fill = temp)) + facet_wrap(~label, ncol = 1) + scale_fill_whitebox_c(palette = "muted")
SpatVector from long to widepivot_wider() "widens" a SpatVector, increasing the number of columns and
decreasing the number of rows. The inverse transformation is
pivot_longer.SpatVector().
## S3 method for class 'SpatVector' pivot_wider( data, ..., id_cols = NULL, id_expand = FALSE, names_from = "name", names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_vary = "fastest", names_expand = FALSE, names_repair = "check_unique", values_from = "value", values_fill = NULL, values_fn = NULL, unused_fn = NULL )## S3 method for class 'SpatVector' pivot_wider( data, ..., id_cols = NULL, id_expand = FALSE, names_from = "name", names_prefix = "", names_sep = "_", names_glue = NULL, names_sort = FALSE, names_vary = "fastest", names_expand = FALSE, names_repair = "check_unique", values_from = "value", values_fill = NULL, values_fn = NULL, unused_fn = NULL )
data |
A |
... |
Additional arguments passed on to methods. |
id_cols |
< Defaults to all columns in Note that " |
id_expand |
Should the values in the |
names_from, values_from
|
< If |
names_prefix |
A regular expression used to remove matching text from the start of each variable name. |
names_sep |
If |
names_glue |
Instead of |
names_sort |
Should the column names be sorted? If |
names_vary |
When
|
names_expand |
Should the values in the |
names_repair |
What happens if the output has invalid column names?
The default, |
values_fill |
Optionally, a (scalar) value that specifies what each
This can be a named list if you want to apply different fill values to different value columns. |
values_fn |
Optionally, a function applied to the value in each cell
in the output. You will typically use this when the combination of
This can be a named list if you want to apply different aggregations
to different |
unused_fn |
Optionally, a function applied to summarize the values from
the unused columns (i.e. columns not identified by The default drops all unused columns from the result. This can be a named list if you want to apply different aggregations to different unused columns.
This is similar to grouping by the |
A SpatVector object.
Implementation of the generic tidyr::pivot_wider() method.
SpatVectorThe geometry column has sticky behavior. This means that the result always
has the geometry of data.
Other tidyr verbs for pivoting:
pivot_longer.SpatVector()
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
replace_na.Spat,
uncount.SpatVector(),
unite.Spat
library(dplyr) library(tidyr) library(ggplot2) cyl <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Add extra row with info xtra <- cyl |> slice(c(2, 3)) |> mutate( label = "extra", value = TRUE ) |> rbind(cyl) |> glimpse() # Pivot by geom xtra |> pivot_wider( id_cols = iso2:name, values_from = value, names_from = label )library(dplyr) library(tidyr) library(ggplot2) cyl <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Add extra row with info xtra <- cyl |> slice(c(2, 3)) |> mutate( label = "extra", value = TRUE ) |> rbind(cyl) |> glimpse() # Pivot by geom xtra |> pivot_wider( id_cols = iso2:name, values_from = value, names_from = label )
A tibble including the color map of 15 gradient palettes.
A tibble of 75 rows and 5 columns with the following fields:
Name of the palette.
Value of the red channel (RGB color mode).
Value of the green channel (RGB color mode).
Value of the blue channel (RGB color mode).
Hex code of the color.
https://leahsmyth.github.io/Princess-Colour-Schemes/index.html.
Other datasets:
cross_blended_hypsometric_tints_db,
grass_db,
hypsometric_tints_db,
volcano2
data("princess_db") princess_db # Select a palette maori <- princess_db |> filter(pal == "maori") f <- system.file("extdata/volcano2.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = maori$hex)data("princess_db") princess_db # Select a palette maori <- princess_db |> filter(pal == "maori") f <- system.file("extdata/volcano2.tif", package = "tidyterra") r <- terra::rast(f) library(ggplot2) p <- ggplot() + geom_spatraster(data = r) + labs(fill = "elevation") p + scale_fill_gradientn(colors = maori$hex)
Extract the WKT version of the CRS associated with a string, number or
sf/Spat* object.
The Well-known text (WKT) representation of coordinate reference systems (CRS) is a character string that identifies precisely the arguments of each CRS. It is the standard used by sf and terra.
pull_crs(.data, ...)pull_crs(.data, ...)
.data |
Input potentially including or representing a CRS. It could be
a |
... |
Ignored. |
Although the WKT representation is the same, the sf and terra APIs differ slightly. For example, sf can do:
sf::st_transform(x, 25830)
While the terra equivalent is:
terra::project(bb, "epsg:25830")
Knowing the WKT helps smooth workflows when working with different packages and object types.
A WKT representation of the corresponding CRS.
A thin wrapper around sf::st_crs() and terra::crs().
terra::crs() and sf::st_crs() to learn how these packages handle
CRS definitions.
Other helpers:
compare_spatrasters(),
is_grouped_spatvector(),
is_regular_grid()
# sf objects sfobj <- sf::st_as_sfc("MULTIPOINT ((0 0), (1 1))", crs = 4326) fromsf1 <- pull_crs(sfobj) fromsf2 <- pull_crs(sf::st_crs(sfobj)) # terra v <- terra::vect(sfobj) r <- terra::rast(v) fromterra1 <- pull_crs(v) fromterra2 <- pull_crs(r) # integers fromint <- pull_crs(4326) # Characters fromchar <- pull_crs("epsg:4326") all( fromsf1 == fromsf2, fromsf2 == fromterra1, fromterra1 == fromterra2, fromterra2 == fromint, fromint == fromchar ) cat(fromsf1)# sf objects sfobj <- sf::st_as_sfc("MULTIPOINT ((0 0), (1 1))", crs = 4326) fromsf1 <- pull_crs(sfobj) fromsf2 <- pull_crs(sf::st_crs(sfobj)) # terra v <- terra::vect(sfobj) r <- terra::rast(v) fromterra1 <- pull_crs(v) fromterra2 <- pull_crs(r) # integers fromint <- pull_crs(4326) # Characters fromchar <- pull_crs("epsg:4326") all( fromsf1 == fromsf2, fromsf2 == fromterra1, fromterra1 == fromterra2, fromterra2 == fromint, fromint == fromchar ) cat(fromsf1)
pull() is similar to $ on a data frame. It is mostly useful because it
looks nicer in pipes and can optionally name the output.
You can extract the geographic coordinates of a SpatRaster.
Use pull(.data, x, xy = TRUE). x and y are reserved
names on terra, since they refer to the geographic coordinates of the layer.
See Examples and section About layer names on as_tibble.Spat().
## S3 method for class 'SpatRaster' pull(.data, var = -1, name = NULL, ...) ## S3 method for class 'SpatVector' pull(.data, var = -1, name = NULL, ...)## S3 method for class 'SpatRaster' pull(.data, var = -1, name = NULL, ...) ## S3 method for class 'SpatVector' pull(.data, var = -1, name = NULL, ...)
.data |
A |
var |
A variable specified as:
The default returns the last layer/attribute (on the assumption that's the column you've created most recently). This argument is taken by expression and supports quasiquotation (you can unquote column names and column locations). |
name |
An optional parameter that specifies the column to be used
as names for a named vector. Specified in a similar manner as |
... |
Arguments passed on to |
A vector the same number of cells/geometries as .data.
On SpatRaster objects, note that the default (na.rm = FALSE) removes
empty cells, so you may need to pass (na.rm = FALSE) to .... See
terra::as.data.frame().
Implementation of the generic dplyr::pull() method. This is done
by coercing the Spat* object to a tibble first (see as_tibble.Spat) and
then using dplyr::pull() method over the tibble.
SpatRasterWhen passing option na.rm = TRUE to ..., only cells with a value
distinct to NA are extracted. See terra::as.data.frame().
If xy = TRUE option is passed to ..., two columns names x and y
(corresponding to the geographic coordinates of each cell) are available
in position 1 and 2. Hence, pull(.data, 1) and
pull(.data, 1, xy = TRUE) return different result.
SpatVectorWhen passing geom = "WKT"/geom = "HEX" to ..., the geometry of the
SpatVector can be pulled passing var = geometry. Similarly to
SpatRaster method, when using geom = "XY" the x,y coordinates can be
pulled with var = x/var = y. See terra::as.data.frame() options.
Other dplyr verbs that operate on columns:
glimpse.Spat,
mutate.Spat,
relocate.Spat,
rename.Spat,
select.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") r <- rast(f) # Extract second layer r |> pull(2) |> head() # With xy the first two cols are `x` (longitude) and `y` (latitude) r |> pull(2, xy = TRUE) |> head() # With renaming r |> mutate(cat = cut(cyl_tile_3, c(0, 100, 300))) |> pull(cyl_tile_3, name = cat) |> head()library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") r <- rast(f) # Extract second layer r |> pull(2) |> head() # With xy the first two cols are `x` (longitude) and `y` (latitude) r |> pull(2, xy = TRUE) |> head() # With renaming r |> mutate(cat = cut(cyl_tile_3, c(0, 100, 300))) |> pull(cyl_tile_3, name = cat) |> head()
SpatVector
reframe() can return any number of rows per group. The geometry of each
group is aggregated and repeated for each row created for that group.
## S3 method for class 'SpatVector' reframe(.data, ..., .by = NULL, .dissolve = TRUE)## S3 method for class 'SpatVector' reframe(.data, ..., .by = NULL, .dissolve = TRUE)
.data |
A |
... |
Name-value pairs of functions. The name will be the name of the variable in the result. The value can be a vector of any length. Unnamed data frame values add multiple columns from a single expression. |
.by |
< |
.dissolve |
Logical. If |
A SpatVector.
Implementation of the generic dplyr::reframe() method.
SpatVectorFor grouped inputs, and for calls using .by, geometries are aggregated per
group. If a group produces more than one row, the aggregated group geometry
is repeated for each output row.
dplyr::reframe(), summarise.SpatVector()
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
mutate.Spat,
rename.Spat,
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on group of rows:
count.SpatVector(),
group_by.SpatVector(),
rowwise.SpatVector(),
summarise.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$grp <- rep(c("A", "B"), length.out = nrow(v)) v |> reframe(value = c(min(as.double(cpro)), max(as.double(cpro))), .by = grp) v |> rowwise() |> reframe(value = 1:2)v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$grp <- rep(c("A", "B"), length.out = nrow(v)) v |> reframe(value = c(min(as.double(cpro)), max(as.double(cpro))), .by = grp) v |> rowwise() |> reframe(value = 1:2)
Use relocate() to change layer/attribute positions, using the same syntax
as select.Spat to make it easy to move blocks of
layers/attributes at once.
## S3 method for class 'SpatRaster' relocate(.data, ..., .before = NULL, .after = NULL) ## S3 method for class 'SpatVector' relocate(.data, ..., .before = NULL, .after = NULL)## S3 method for class 'SpatRaster' relocate(.data, ..., .before = NULL, .after = NULL) ## S3 method for class 'SpatVector' relocate(.data, ..., .before = NULL, .after = NULL)
.data |
A |
... |
< |
.before, .after
|
< |
A Spat* object of the same class as .data. See Methods.
terra::subset(data, c("name_layer", "name_other_layer"))
Implementation of the generic dplyr::relocate() method.
SpatRasterRelocate layers of a SpatRaster.
SpatVectorThe result is a SpatVector with the attributes on a different order.
Other dplyr verbs that operate on columns:
glimpse.Spat,
mutate.Spat,
pull.Spat,
rename.Spat,
select.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") spatrast <- rast(f) |> mutate(aa = 1, bb = 2, cc = 3) names(spatrast) spatrast |> relocate(bb, .before = cyl_tile_3) |> relocate(cyl_tile_1, .after = last_col())library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") spatrast <- rast(f) |> mutate(aa = 1, bb = 2, cc = 3) names(spatrast) spatrast |> relocate(bb, .before = cyl_tile_3) |> relocate(cyl_tile_1, .after = last_col())
rename() changes the names of individual layers/attributes using
new_name = old_name syntax. rename_with() renames layers/attributes
using a function.
## S3 method for class 'SpatRaster' rename(.data, ...) ## S3 method for class 'SpatRaster' rename_with(.data, .fn, .cols = everything(), ...) ## S3 method for class 'SpatVector' rename(.data, ...) ## S3 method for class 'SpatVector' rename_with(.data, .fn, .cols = everything(), ...)## S3 method for class 'SpatRaster' rename(.data, ...) ## S3 method for class 'SpatRaster' rename_with(.data, .fn, .cols = everything(), ...) ## S3 method for class 'SpatVector' rename(.data, ...) ## S3 method for class 'SpatVector' rename_with(.data, .fn, .cols = everything(), ...)
.data |
A |
... |
For For |
.fn |
A function used to transform the selected |
.cols |
< |
A Spat* object of the same class as .data. See Methods.
names(Spat*) <- c("a", "b", "c")
Implementation of the generic dplyr::rename() method.
SpatRasterRename layers of a SpatRaster.
SpatVectorThe result is a SpatVector with the renamed attributes on the function
call.
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
mutate.Spat,
reframe.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on columns:
glimpse.Spat,
mutate.Spat,
pull.Spat,
relocate.Spat,
select.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") spatrast <- rast(f) |> mutate(aa = 1, bb = 2, cc = 3) spatrast spatrast |> rename( this_first = cyl_tile_1, this_second = cyl_tile_2 ) spatrast |> rename_with( toupper, .cols = starts_with("c") )library(terra) f <- system.file("extdata/cyl_tile.tif", package = "tidyterra") spatrast <- rast(f) |> mutate(aa = 1, bb = 2, cc = 3) spatrast spatrast |> rename( this_first = cyl_tile_1, this_second = cyl_tile_2 ) spatrast |> rename_with( toupper, .cols = starts_with("c") )
NAs with specified valuesReplace NAs values on layers/attributes with specified values
## S3 method for class 'SpatRaster' replace_na(data, replace = list(), ...) ## S3 method for class 'SpatVector' replace_na(data, replace, ...)## S3 method for class 'SpatRaster' replace_na(data, replace = list(), ...) ## S3 method for class 'SpatVector' replace_na(data, replace, ...)
data |
A |
replace |
A named list of values, with one value for each
layer/attribute that has missing values to be replaced. Each value in
|
... |
Additional arguments for methods. Currently unused. |
A Spat* object of the same class as data. See Methods.
Use r[is.na(r)] <- <replacement>
Other tidyr verbs for handling missing values:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector()
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
uncount.SpatVector(),
unite.Spat
library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) r |> plot() r |> replace_na(list(tavg_04 = 6, tavg_06 = 20)) |> plot()library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) r |> plot() r |> replace_na(list(tavg_04 = 6, tavg_06 = 20)) |> plot()
Spat* objectsDetermine packages required by Spat* objects.
## S3 method for class 'SpatRaster' required_pkgs(x, ...) ## S3 method for class 'SpatVector' required_pkgs(x, ...) ## S3 method for class 'SpatGraticule' required_pkgs(x, ...) ## S3 method for class 'SpatExtent' required_pkgs(x, ...)## S3 method for class 'SpatRaster' required_pkgs(x, ...) ## S3 method for class 'SpatVector' required_pkgs(x, ...) ## S3 method for class 'SpatGraticule' required_pkgs(x, ...) ## S3 method for class 'SpatExtent' required_pkgs(x, ...)
x |
A |
... |
Ignored by these methods. |
A character string of packages that are required.
Implementation of generics::required_pkgs() method.
Other generics methods:
glance.Spat,
tidy.Spat
file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) r <- rast(file_path) # With rasters r required_pkgs(r) # With vectors v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v required_pkgs(v)file_path <- system.file("extdata/cyl_temp.tif", package = "tidyterra") library(terra) r <- rast(file_path) # With rasters r required_pkgs(r) # With vectors v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v required_pkgs(v)
SpatVector objectsMethods for the dplyr::rows_insert() family on SpatVector objects.
## S3 method for class 'SpatVector' rows_insert( x, y, by = NULL, ..., conflict = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_append(x, y, ..., copy = FALSE, in_place = FALSE) ## S3 method for class 'SpatVector' rows_update( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_patch( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_upsert(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) ## S3 method for class 'SpatVector' rows_delete( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE )## S3 method for class 'SpatVector' rows_insert( x, y, by = NULL, ..., conflict = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_append(x, y, ..., copy = FALSE, in_place = FALSE) ## S3 method for class 'SpatVector' rows_update( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_patch( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE ) ## S3 method for class 'SpatVector' rows_upsert(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) ## S3 method for class 'SpatVector' rows_delete( x, y, by = NULL, ..., unmatched = c("error", "ignore"), copy = FALSE, in_place = FALSE )
x |
A |
y |
A data frame, |
by |
An unnamed character vector giving the key columns. The key columns
must exist in both By default, we use the first column in |
... |
Other parameters passed onto methods. |
conflict |
For One of:
|
copy |
If |
in_place |
Should When |
unmatched |
For One of:
|
A SpatVector.
Implementation of the generic dplyr::rows_insert() family for
SpatVector objects.
SpatVectorRow operations update attributes while preserving the geometry column. When inserting data frame rows without geometry, the output contains empty geometries for the new rows.
Other dplyr verbs that operate on rows:
arrange.SpatVector(),
distinct.SpatVector(),
filter.Spat,
slice.Spat
Other dplyr verbs that operate on pairs Spat*/data.frame:
bind_cols.SpatVector,
bind_rows.SpatVector,
cross_join.SpatVector(),
filter-joins.SpatVector,
mutate-joins.SpatVector,
nest_join.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rowwise.SpatVector(),
select.Spat,
slice.Spat,
summarise.SpatVector()
v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) rows_update( v, tibble::tibble(cpro = "05", name = "New name"), by = "cpro" ) rows_insert( v, tibble::tibble(cpro = "99", name = "New province"), by = "cpro" )v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) rows_update( v, tibble::tibble(cpro = "05", name = "New name"), by = "cpro" ) rows_insert( v, tibble::tibble(cpro = "99", name = "New province"), by = "cpro" )
SpatVector objects by rowsrowwise() allows you to compute on a SpatVector one row at a time.
This is most useful when a vectorised function does not exist.
Most dplyr verb implementations in tidyterra preserve
row-wise grouping. The exception is summarise.SpatVector(), which returns
a grouped SpatVector. You can explicitly ungroup with
ungroup.SpatVector() or as_tibble() or convert to a grouped SpatVector
with group_by.SpatVector().
## S3 method for class 'SpatVector' rowwise(data, ...)## S3 method for class 'SpatVector' rowwise(data, ...)
data |
A |
... |
< NB: unlike |
See Details on dplyr::rowwise().
The same SpatVector object with updated grouping metadata.
Implementation of the generic dplyr::rowwise() function for
SpatVector objects.
When mixing terra and dplyr syntax on a
row-wise SpatVector (i.e. subsetting a SpatVector like v[1:3,1:2]),
the groups attribute can be corrupted. tidyterra tries to
regenerate the SpatVector. This is triggered the next time you use a
dplyr verb on your SpatVector.
Note also that some operations, such as terra::spatSample(), create a new
SpatVector. In these cases, the result does not preserve the groups
attribute. Use rowwise.SpatVector() to re-group.
Other dplyr verbs that operate on group of rows:
count.SpatVector(),
group_by.SpatVector(),
reframe.SpatVector(),
summarise.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
select.Spat,
slice.Spat,
summarise.SpatVector()
library(terra) library(dplyr) v <- terra::vect(system.file("shape/nc.shp", package = "sf")) # Select new births nb <- v |> select(starts_with("NWBIR")) |> glimpse() # Compute the mean of NWBIR on each geometry nb |> rowwise() |> mutate(nb_mean = mean(c(NWBIR74, NWBIR79))) # Additional examples # use c_across() to more easily select many variables nb |> rowwise() |> mutate(m = mean(c_across(NWBIR74:NWBIR79))) # Compute the minimum of x and y in each row nb |> rowwise() |> mutate(min = min(c_across(NWBIR74:NWBIR79))) # Summarising v |> rowwise() |> summarise(mean_bir = mean(BIR74, BIR79)) |> glimpse() |> autoplot(aes(fill = mean_bir)) # Supply a variable to be kept v |> mutate(id2 = as.integer(CNTY_ID / 100)) |> rowwise(id2) |> summarise(mean_bir = mean(BIR74, BIR79)) |> glimpse() |> autoplot(aes(fill = as.factor(id2)))library(terra) library(dplyr) v <- terra::vect(system.file("shape/nc.shp", package = "sf")) # Select new births nb <- v |> select(starts_with("NWBIR")) |> glimpse() # Compute the mean of NWBIR on each geometry nb |> rowwise() |> mutate(nb_mean = mean(c(NWBIR74, NWBIR79))) # Additional examples # use c_across() to more easily select many variables nb |> rowwise() |> mutate(m = mean(c_across(NWBIR74:NWBIR79))) # Compute the minimum of x and y in each row nb |> rowwise() |> mutate(min = min(c_across(NWBIR74:NWBIR79))) # Summarising v |> rowwise() |> summarise(mean_bir = mean(BIR74, BIR79)) |> glimpse() |> autoplot(aes(fill = mean_bir)) # Supply a variable to be kept v |> mutate(id2 = as.integer(CNTY_ID / 100)) |> rowwise(id2) |> summarise(mean_bir = mean(BIR74, BIR79)) |> glimpse() |> autoplot(aes(fill = as.factor(id2)))
Implementation based on the Wikipedia Colorimetric conventions for topographic maps.
Three scales are provided:
scale_*_wiki_d(): For discrete values.
scale_*_wiki_c(): For continuous values.
scale_*_wiki_b(): For binning continuous values.
Additionally, a color palette wiki.colors() is provided. See also
grDevices::terrain.colors() for details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_wiki_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_wiki_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_wiki_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_wiki_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_wiki_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_wiki_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) wiki.colors(n, alpha = 1, rev = FALSE)scale_fill_wiki_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_wiki_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_wiki_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_wiki_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_wiki_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_wiki_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) wiki.colors(n, alpha = 1, rev = FALSE)
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
na.translate |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
drop |
Logical. If |
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
terra::plot(), ggplot2::scale_fill_viridis_c()
See also ggplot2 docs on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_cross_blended,
scale_grass,
scale_hypso,
scale_princess,
scale_terrain,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = wiki.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_wiki_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_wiki_b(breaks = seq(70, 200, 10)) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_wiki_d(na.value = "gray10")filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = wiki.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_wiki_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_wiki_b(breaks = seq(70, 200, 10)) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_wiki_d(na.value = "gray10")
SpatRaster
Some categorical SpatRaster objects may have an associated color table.
This function extract those values. These functions generates scales and
vector of colors based on the color table terra::coltab() associated to a
SpatRaster.
You can also get a vector of colors named with the corresponding
factor with get_coltab_pal().
Additional arguments ... are passed to
ggplot2::discrete_scale().
Note that tidyterra documents only a selection of these
additional arguments, check ggplot2::discrete_scale() to see the full
range of arguments accepted.
scale_fill_coltab( data, ..., alpha = NA, na.translate = FALSE, na.value = "transparent", drop = TRUE ) scale_colour_coltab( data, ..., alpha = NA, na.translate = FALSE, na.value = "transparent", drop = TRUE ) get_coltab_pal(x)scale_fill_coltab( data, ..., alpha = NA, na.translate = FALSE, na.value = "transparent", drop = TRUE ) scale_colour_coltab( data, ..., alpha = NA, na.translate = FALSE, na.value = "transparent", drop = TRUE ) get_coltab_pal(x)
data, x
|
A |
... |
Arguments passed on to
|
alpha |
The alpha transparency: could be |
na.translate |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
drop |
Logical. If |
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
terra::coltab(), ggplot2::discrete_scale(),
ggplot2::scale_fill_manual(),
library(terra) # Geological Eras # Spanish Geological Survey (IGME) r <- rast(system.file("extdata/cyl_era.tif", package = "tidyterra")) plot(r) # Get coltab coltab_pal <- get_coltab_pal(r) coltab_pal # With ggplot2 + tidyterra library(ggplot2) gg <- ggplot() + geom_spatraster(data = r) # Default plot gg # With coltabs gg + scale_fill_coltab(data = r)library(terra) # Geological Eras # Spanish Geological Survey (IGME) r <- rast(system.file("extdata/cyl_era.tif", package = "tidyterra")) plot(r) # Get coltab coltab_pal <- get_coltab_pal(r) coltab_pal # With ggplot2 + tidyterra library(ggplot2) gg <- ggplot() + geom_spatraster(data = r) # Default plot gg # With coltabs gg + scale_fill_coltab(data = r)
Implementation of the cross blended hypsometric gradients presented on doi:10.14714/CP69.20. The following fill scales and palettes are provided:
scale_*_cross_blended_d(): For discrete values.
scale_*_cross_blended_c(): For continuous values.
scale_*_cross_blended_b(): For binning continuous values.
cross_blended.colors(): A gradient color palette. See also
grDevices::terrain.colors() for details.
An additional set of scales is provided. These scales can act as hypsometric (or bathymetric) tints.
scale_*_cross_blended_tint_d(): For discrete values.
scale_*_cross_blended_tint_c(): For continuous values.
scale_*_cross_blended_tint_b(): For binning continuous values.
cross_blended.colors2(): A gradient color palette. See also
grDevices::terrain.colors() for details.
See Details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_cross_blended_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_cross_blended_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_cross_blended_c( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_cross_blended_c( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_cross_blended_b( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_cross_blended_b( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) cross_blended.colors(n, palette = "cold_humid", alpha = 1, rev = FALSE) scale_fill_cross_blended_tint_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_cross_blended_tint_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_cross_blended_tint_c( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_colour_cross_blended_tint_c( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_fill_cross_blended_tint_b( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) scale_colour_cross_blended_tint_b( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) cross_blended.colors2(n, palette = "cold_humid", alpha = 1, rev = FALSE)scale_fill_cross_blended_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_cross_blended_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_cross_blended_c( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_cross_blended_c( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_cross_blended_b( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_cross_blended_b( palette = "cold_humid", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) cross_blended.colors(n, palette = "cold_humid", alpha = 1, rev = FALSE) scale_fill_cross_blended_tint_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_cross_blended_tint_d( palette = "cold_humid", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_cross_blended_tint_c( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_colour_cross_blended_tint_c( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_fill_cross_blended_tint_b( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) scale_colour_cross_blended_tint_b( palette = "cold_humid", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) cross_blended.colors2(n, palette = "cold_humid", alpha = 1, rev = FALSE)
palette |
A valid palette name. The name is matched to the list of
available palettes, ignoring upper vs. lower case. See
cross_blended_hypsometric_tints_db for more info. The available values
are listed below.
|
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
values |
if colours should not be evenly positioned along the gradient
this vector gives the position (between 0 and 1) for each colour in the
|
limits |
One of:
|
On scale_*_cross_blended_tint_* palettes, the position of the gradients
and the limits of the palette are redefined. Instead of treating the color
palette as a continuous gradient, they are rescaled to act as a hypsometric
tint. A rough description of these tints are:
Blue colors: Negative values.
Green colors: 0 to 1.000 values.
Browns: 1000 to 4.000 values.
Whites: Values higher than 4.000.
The following orientation varies depending on the palette definition (see cross_blended_hypsometric_tints_db for an example of how this can be achieved).
Note that the setup of the palette may not always be suitable for your
specific data. For example, a SpatRaster of small parts of the globe (and
with a limited range of elevations) may not be well represented. As an
example, a SpatRaster with a range of values on [100, 200] appears
almost as a uniform color. This can be adjusted using the limits/values
arguments.
When passing the limits argument to scale_*_cross_blended_tint_*, the
colors are restricted to those specified by this argument, keeping the
distribution of the tint. You can combine this with oob (i.e.
oob = scales::oob_squish) to avoid blank pixels in the plot.
cross_blended.colors2() provides a gradient color palette where the
distance between colors is different depending of the type of color.
In contrast, cross_blended.colors() provides a uniform gradient across
colors. See Examples.
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
Patterson, T., & Jenny, B. (2011). The Development and Rationale of Cross-blended Hypsometric Tints. Cartographic Perspectives, (69), 31 - 46. doi:10.14714/CP69.20.
Patterson, T. (2004). Using Cross-blended Hypsometric Tints for Generalized Environmental Mapping. Online, Accessed June 10, 2022.
cross_blended_hypsometric_tints_db, terra::plot(),
terra::minmax(), ggplot2::scale_fill_viridis_c().
See also ggplot2 docs on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_grass,
scale_hypso,
scale_princess,
scale_terrain,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = cross_blended.colors(100, palette = "arid")) # Palette with uneven colors plot(volcano2_rast, col = cross_blended.colors2(100, palette = "arid")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_c(palette = "cold_humid") # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_cross_blended_tint_c( palette = "warm_humid", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = TRUE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_b(breaks = seq(70, 200, 25), palette = "arid") # With breaks ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_b( breaks = seq(75, 200, 25), palette = "arid" ) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_cross_blended_d(na.value = "gray10", palette = "cold_humid") # Tint version ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_cross_blended_tint_d( na.value = "gray10", palette = "cold_humid" ) # Display all the cross-blended palettes pals <- unique(cross_blended_hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = cross_blended.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Display all the cross-blended palettes on version 2 pals <- unique(cross_blended_hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = cross_blended.colors2(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = cross_blended.colors(100, palette = "arid")) # Palette with uneven colors plot(volcano2_rast, col = cross_blended.colors2(100, palette = "arid")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_c(palette = "cold_humid") # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_cross_blended_tint_c( palette = "warm_humid", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = TRUE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_b(breaks = seq(70, 200, 25), palette = "arid") # With breaks ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_cross_blended_b( breaks = seq(75, 200, 25), palette = "arid" ) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_cross_blended_d(na.value = "gray10", palette = "cold_humid") # Tint version ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_cross_blended_tint_d( na.value = "gray10", palette = "cold_humid" ) # Display all the cross-blended palettes pals <- unique(cross_blended_hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = cross_blended.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Display all the cross-blended palettes on version 2 pals <- unique(cross_blended_hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = cross_blended.colors2(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)
Implementation of GRASS color tables. The following fill scales and palettes are provided:
scale_*_grass_d(): For discrete values.
scale_*_grass_c(): For continuous values.
scale_*_grass_b(): For binning continuous values.
grass.colors(): Gradient color palette. See also
grDevices::terrain.colors() for details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a subset of these additional arguments, so see the ggplot2 functions listed above for the full range.
These palettes implement terra::map.pal(), the default color palettes used
by terra::plot() in terra versions above 1.7.78.
scale_fill_grass_d( palette = "viridis", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_grass_d( palette = "viridis", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_grass_c( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "colourbar" ) scale_colour_grass_c( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "colourbar" ) scale_fill_grass_b( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "coloursteps" ) scale_colour_grass_b( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "coloursteps" ) grass.colors(n, palette = "viridis", alpha = 1, rev = FALSE)scale_fill_grass_d( palette = "viridis", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_grass_d( palette = "viridis", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_grass_c( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "colourbar" ) scale_colour_grass_c( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "colourbar" ) scale_fill_grass_b( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "coloursteps" ) scale_colour_grass_b( palette = "viridis", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, use_grass_range = TRUE, na.value = "transparent", guide = "coloursteps" ) grass.colors(n, palette = "viridis", alpha = 1, rev = FALSE)
palette |
A valid palette name. The name is matched to the list of available palettes, ignoring upper vs. lower case. See grass_db for more info. |
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
values |
if colours should not be evenly positioned along the gradient
this vector gives the position (between 0 and 1) for each colour in the
|
limits |
One of:
|
use_grass_range |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
Some palettes are mapped by default to a specific range of values (see
grass_db). Set use_grass_range = FALSE to map the color scales to the
range of values of the color/fill aesthetics. See Examples.
When passing the limits argument, the colors are restricted to those
specified by this argument, keeping the distribution of the palette. You can
combine this with oob (i.e. oob = scales::oob_squish) to avoid blank
pixels in the plot.
The corresponding ggplot2 layer with the values applied to the
fill/colour aes().
Derived from https://github.com/OSGeo/grass/tree/main/lib/gis/colors. See also r.color - GRASS GIS Manual.
GRASS Development Team (2024). Geographic Resources Analysis Support System (GRASS) Software, Version 8.3.2. Open Source Geospatial Foundation, USA. https://grass.osgeo.org.
grass_db, terra::plot(),
terra::minmax(), ggplot2::scale_fill_viridis_c().
See also ggplot2 docs on additional ... arguments:
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_cross_blended,
scale_hypso,
scale_princess,
scale_terrain,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = grass.colors(100, palette = "haxby")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_c(palette = "terrain") # Use with no default limits ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_c(palette = "terrain", use_grass_range = FALSE) # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_grass_c( palette = "srtm_plus", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = FALSE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_b(breaks = seq(70, 200, 25), palette = "sepia") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_grass_d(palette = "soilmoisture") # Display all the GRASS palettes data("grass_db") pals_all <- unique(grass_db$pal) # In batches pals <- pals_all[c(1:25)] # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = grass.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Second batch pals <- pals_all[-c(1:25)] ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = grass.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = grass.colors(100, palette = "haxby")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_c(palette = "terrain") # Use with no default limits ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_c(palette = "terrain", use_grass_range = FALSE) # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_grass_c( palette = "srtm_plus", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = FALSE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_grass_b(breaks = seq(70, 200, 25), palette = "sepia") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_grass_d(palette = "soilmoisture") # Display all the GRASS palettes data("grass_db") pals_all <- unique(grass_db$pal) # In batches pals <- pals_all[c(1:25)] # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = grass.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Second batch pals <- pals_all[-c(1:25)] ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = grass.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)
Implementation of a selection of gradient palettes available in cpt-city.
The following scales and palettes are provided:
scale_*_hypso_d(): For discrete values.
scale_*_hypso_c(): For continuous values.
scale_*_hypso_b(): For binning continuous values.
hypso.colors(): A gradient color palette. See also
grDevices::terrain.colors() for details.
An additional set of scales is provided. These scales can act as hypsometric (or bathymetric) tints.
scale_*_hypso_tint_d(): For discrete values.
scale_*_hypso_tint_c(): For continuous values.
scale_*_hypso_tint_b(): For binning continuous values.
hypso.colors2(): A gradient color palette. See also
grDevices::terrain.colors() for details.
See Details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_hypso_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_hypso_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_hypso_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_hypso_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_hypso_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_hypso_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) hypso.colors(n, palette = "etopo1_hypso", alpha = 1, rev = FALSE) scale_fill_hypso_tint_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_hypso_tint_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_hypso_tint_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_colour_hypso_tint_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_fill_hypso_tint_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) scale_colour_hypso_tint_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) hypso.colors2(n, palette = "etopo1_hypso", alpha = 1, rev = FALSE)scale_fill_hypso_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_hypso_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_hypso_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_hypso_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_hypso_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_hypso_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) hypso.colors(n, palette = "etopo1_hypso", alpha = 1, rev = FALSE) scale_fill_hypso_tint_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_hypso_tint_d( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_hypso_tint_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_colour_hypso_tint_c( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "colourbar" ) scale_fill_hypso_tint_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) scale_colour_hypso_tint_b( palette = "etopo1_hypso", ..., alpha = 1, direction = 1, values = NULL, limits = NULL, na.value = "transparent", guide = "coloursteps" ) hypso.colors2(n, palette = "etopo1_hypso", alpha = 1, rev = FALSE)
palette |
A valid palette name. The name is matched to the list of
available palettes, ignoring upper vs. lower case. See
hypsometric_tints_db for more info. The available values are listed
below.
|
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
values |
if colours should not be evenly positioned along the gradient
this vector gives the position (between 0 and 1) for each colour in the
|
limits |
One of:
|
On scale_*_hypso_tint_* palettes, the position of the gradients and
the limits of the palette are redefined. Instead of treating the color
palette as a continuous gradient, they are rescaled to act as a hypsometric
tint. A rough description of these tints are:
Blue colors: Negative values.
Green colors: 0 to 1.000 values.
Browns: 1000 to 4.000 values.
Whites: Values higher than 4.000.
The following orientation varies depending on the palette definition (see hypsometric_tints_db for an example of how this can be achieved).
Note that the setup of the palette may not always be suitable for your
specific data. For example, a SpatRaster of small parts of the globe (and
with a limited range of elevations) may not be well represented. As an
example, a SpatRaster with a range of values on [100, 200] appears
almost as a uniform color. This can be adjusted using the limits/values
arguments.
When passing the limits argument to scale_*_hypso_tint_*, the colors are
restricted to those specified by this argument, keeping the distribution of
the tint. You can combine this with oob (i.e. oob = scales::oob_squish)
to avoid blank pixels in the plot.
hypso.colors2() provides a gradient color palette where the distance
between colors is different depending of the type of color. In contrast,
hypso.colors() provides a uniform gradient across colors. See
Examples.
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
cpt-city: https://phillips.shef.ac.uk/pub/cpt-city/.
hypsometric_tints_db, terra::plot(), terra::minmax(),
ggplot2::scale_fill_viridis_c()
See also ggplot2 docs on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_cross_blended,
scale_grass,
scale_princess,
scale_terrain,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = hypso.colors(100, palette = "wiki-2.0_hypso")) # Palette with uneven colors plot(volcano2_rast, col = hypso.colors2(100, palette = "wiki-2.0_hypso")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_c(palette = "colombia_hypso") # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_hypso_tint_c( palette = "etopo1", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = TRUE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_b(breaks = seq(70, 200, 25), palette = "wiki-2.0_hypso") # With breaks ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_b( breaks = seq(75, 200, 25), palette = "wiki-2.0_hypso" ) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_hypso_d(na.value = "gray10", palette = "dem_poster") # Tint version ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_hypso_tint_d(na.value = "gray10", palette = "dem_poster") # Display all the cpl_city palettes pals <- unique(hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = hypso.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Display all the cpl_city palettes on version 2 pals <- unique(hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = hypso.colors2(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = hypso.colors(100, palette = "wiki-2.0_hypso")) # Palette with uneven colors plot(volcano2_rast, col = hypso.colors2(100, palette = "wiki-2.0_hypso")) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_c(palette = "colombia_hypso") # Full map with true tints f_asia <- system.file("extdata/asia.tif", package = "tidyterra") asia <- rast(f_asia) ggplot() + geom_spatraster(data = asia) + scale_fill_hypso_tint_c( palette = "etopo1", labels = scales::label_number(), breaks = c(-10000, 0, 5000, 8000), guide = guide_colorbar(reverse = TRUE) ) + labs(fill = "elevation (m)") + 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" ) # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_b(breaks = seq(70, 200, 25), palette = "wiki-2.0_hypso") # With breaks ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_hypso_b( breaks = seq(75, 200, 25), palette = "wiki-2.0_hypso" ) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_hypso_d(na.value = "gray10", palette = "dem_poster") # Tint version ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_hypso_tint_d(na.value = "gray10", palette = "dem_poster") # Display all the cpl_city palettes pals <- unique(hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = hypso.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar) # Display all the cpl_city palettes on version 2 pals <- unique(hypsometric_tints_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = hypso.colors2(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)
Implementation of the gradient palettes presented in https://leahsmyth.github.io/Princess-Colour-Schemes/index.html. Three scales are provided:
scale_*_princess_d(): For discrete values.
scale_*_princess_c(): For continuous values.
scale_*_princess_b(): For binning continuous values.
Additionally, a color palette princess.colors() is provided. See also
grDevices::terrain.colors() for details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_princess_d( palette = "snow", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_princess_d( palette = "snow", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_princess_c( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_princess_c( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_princess_b( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_princess_b( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) princess.colors(n, palette = "snow", alpha = 1, rev = FALSE)scale_fill_princess_d( palette = "snow", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_princess_d( palette = "snow", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_princess_c( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_princess_c( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_princess_b( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_princess_b( palette = "snow", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) princess.colors(n, palette = "snow", alpha = 1, rev = FALSE)
palette |
A valid palette name. The name is matched to the list of
available palettes, ignoring upper vs. lower case. The available values
are listed below.
|
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
https://github.com/LeahSmyth/Princess-Colour-Schemes.
terra::plot(), ggplot2::scale_fill_viridis_c()
See also ggplot2 docs on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_cross_blended,
scale_grass,
scale_hypso,
scale_terrain,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = princess.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_princess_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_princess_b(breaks = seq(70, 200, 10), palette = "denmark") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_princess_d(na.value = "gray10", palette = "maori") # Display all the princess palettes pals <- unique(princess_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = princess.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = princess.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_princess_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_princess_b(breaks = seq(70, 200, 10), palette = "denmark") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_princess_d(na.value = "gray10", palette = "maori") # Display all the princess palettes pals <- unique(princess_db$pal) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = princess.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)
Implementation of the classic color palette terrain.colors():
scale_*_terrain_d(): For discrete values.
scale_*_terrain_c(): For continuous values.
scale_*_terrain_b(): For binning continuous values.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_terrain_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_terrain_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_terrain_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_terrain_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_terrain_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_terrain_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" )scale_fill_terrain_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_terrain_d( ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_terrain_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_terrain_c( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_terrain_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_terrain_b( ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" )
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
terra::plot(), ggplot2::scale_fill_viridis_c() and ggplot2 docs
on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_cross_blended,
scale_grass,
scale_hypso,
scale_princess,
scale_whitebox
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_terrain_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_terrain_b(breaks = seq(70, 200, 10)) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_terrain_d(na.value = "gray10")filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_terrain_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_terrain_b(breaks = seq(70, 200, 10)) # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_terrain_d(na.value = "gray10")
Implementation of the gradient palettes provided by WhiteboxTools. Three scales are provided:
scale_*_whitebox_d(): For discrete values.
scale_*_whitebox_c(): For continuous values.
scale_*_whitebox_b(): For binning continuous values.
Additionally, a color palette whitebox.colors() is provided. See also
grDevices::terrain.colors() for details.
Additional arguments ... are passed to:
Discrete values: ggplot2::discrete_scale().
Continuous values: ggplot2::continuous_scale().
Binned continuous values: ggplot2::binned_scale().
Note that tidyterra documents only a selection of these additional arguments, check the ggplot2 functions listed above to see the full range of arguments accepted by these scales.
scale_fill_whitebox_d( palette = "high_relief", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_whitebox_d( palette = "high_relief", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_whitebox_c( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_whitebox_c( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_whitebox_b( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_whitebox_b( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) whitebox.colors(n, palette = "high_relief", alpha = 1, rev = FALSE)scale_fill_whitebox_d( palette = "high_relief", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_colour_whitebox_d( palette = "high_relief", ..., alpha = 1, direction = 1, na.translate = FALSE, drop = TRUE ) scale_fill_whitebox_c( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_colour_whitebox_c( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "colourbar" ) scale_fill_whitebox_b( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) scale_colour_whitebox_b( palette = "high_relief", ..., alpha = 1, direction = 1, na.value = "transparent", guide = "coloursteps" ) whitebox.colors(n, palette = "high_relief", alpha = 1, rev = FALSE)
palette |
A valid palette name. The name is matched to the list of
available palettes, ignoring upper vs. lower case. The available values
are listed below.
|
... |
Arguments passed on to
|
alpha |
The alpha transparency, a number in [0,1], see argument alpha in
|
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
na.translate |
Logical. If |
drop |
Logical. If |
na.value |
Missing values will be replaced with this value. By default,
tidyterra uses |
guide |
A function used to create a guide or its name. See
|
n |
the number of colors ( |
rev |
logical indicating whether the ordering of the colors should be reversed. |
The corresponding ggplot2 layer with the values applied to the
fill/colour aesthetics.
https://github.com/jblindsay/whitebox-tools, under MIT License. Copyright (c) 2017-2021 John Lindsay.
terra::plot(), ggplot2::scale_fill_viridis_c()
See also ggplot2 docs on additional ... arguments.
Other gradient scales and palettes for hypsometry:
scale_color_coltab(),
scale_cross_blended,
scale_grass,
scale_hypso,
scale_princess,
scale_terrain
filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = whitebox.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_whitebox_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_whitebox_b(breaks = seq(70, 200, 10), palette = "atlas") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_whitebox_d(na.value = "gray10", palette = "soft") # Display all the whitebox palettes pals <- c( "atlas", "high_relief", "arid", "soft", "muted", "purple", "viridi", "gn_yl", "pi_y_g", "bl_yl_rd", "deep" ) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = whitebox.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)filepath <- system.file("extdata/volcano2.tif", package = "tidyterra") library(terra) volcano2_rast <- rast(filepath) # Palette plot(volcano2_rast, col = whitebox.colors(100)) library(ggplot2) ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_whitebox_c() # Binned ggplot() + geom_spatraster(data = volcano2_rast) + scale_fill_whitebox_b(breaks = seq(70, 200, 10), palette = "atlas") # With discrete values factor <- volcano2_rast |> mutate(cats = cut(elevation, breaks = c(100, 120, 130, 150, 170, 200), labels = c( "Very Low", "Low", "Average", "High", "Very High" ) )) ggplot() + geom_spatraster(data = factor, aes(fill = cats)) + scale_fill_whitebox_d(na.value = "gray10", palette = "soft") # Display all the whitebox palettes pals <- c( "atlas", "high_relief", "arid", "soft", "muted", "purple", "viridi", "gn_yl", "pi_y_g", "bl_yl_rd", "deep" ) # Helper fun for plotting ncols <- 128 rowcol <- grDevices::n2mfrow(length(pals)) opar <- par(no.readonly = TRUE) par(mfrow = rowcol, mar = rep(1, 4)) for (i in pals) { image( x = seq(1, ncols), y = 1, z = as.matrix(seq(1, ncols)), col = whitebox.colors(ncols, i), main = i, ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) } par(opar)
Spat* objectsSelect (and optionally rename) attributes/layers in Spat* objects, using a
concise mini-language. See Methods.
## S3 method for class 'SpatRaster' select(.data, ...) ## S3 method for class 'SpatVector' select(.data, ...)## S3 method for class 'SpatRaster' select(.data, ...) ## S3 method for class 'SpatVector' select(.data, ...)
.data |
A |
... |
< |
A Spat* object of the same class as .data. See Methods.
Implementation of the generic dplyr::select() method.
SpatRasterSelect (and rename) layers of a SpatRaster. The result is a SpatRaster
with the same extent, resolution and CRS as .data. Only the number (and
possibly the name) of layers is modified.
SpatVectorThe result is a SpatVector with the selected (and possibly renamed)
attributes on the function call.
dplyr::select(), terra::subset()
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
mutate.Spat,
reframe.SpatVector(),
rename.Spat,
slice.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on columns:
glimpse.Spat,
mutate.Spat,
pull.Spat,
relocate.Spat,
rename.Spat
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
slice.Spat,
summarise.SpatVector()
library(terra) # SpatRaster method spatrast <- rast( crs = "EPSG:3857", nrows = 10, ncols = 10, extent = c(100, 200, 100, 200), nlyr = 6, vals = seq_len(10 * 10 * 6) ) spatrast |> select(1) # By name spatrast |> select(lyr.1:lyr.4) # Rename spatrast |> select(a = lyr.1, c = lyr.6) # SpatVector method f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) v v |> select(1, 3) v |> select(iso2, name2 = cpro)library(terra) # SpatRaster method spatrast <- rast( crs = "EPSG:3857", nrows = 10, ncols = 10, extent = c(100, 200, 100, 200), nlyr = 6, vals = seq_len(10 * 10 * 6) ) spatrast |> select(1) # By name spatrast |> select(lyr.1:lyr.4) # Rename spatrast |> select(a = lyr.1, c = lyr.6) # SpatVector method f <- system.file("extdata/cyl.gpkg", package = "tidyterra") v <- vect(f) v v |> select(1, 3) v |> select(iso2, name2 = cpro)
slice() methods let you index cells/rows/columns/geometries by their
(integer) locations. They allow you to select, remove or duplicate those
dimensions of a Spat* object.
If you want to slice by geographic coordinates, use filter.SpatRaster().
It includes helpers for common use cases:
slice_head() and slice_tail() select the first or last
cells/geometries.
slice_sample() randomly selects cells/geometries.
slice_rows() and slice_cols() subset entire rows or columns of a
SpatRaster.
slice_colrows() subsets regions of the SpatRaster by row and column
position of a SpatRaster.
You can get a skeleton of your SpatRaster with the cell, column and row
index with as_coordinates().
See Methods for details.
## S3 method for class 'SpatRaster' slice(.data, ..., .preserve = FALSE, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice(.data, ..., .by = NULL, .preserve = FALSE) ## S3 method for class 'SpatRaster' slice_head(.data, ..., n, prop, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice_head(.data, ..., n, prop, by = NULL) ## S3 method for class 'SpatRaster' slice_tail(.data, ..., n, prop, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice_tail(.data, ..., n, prop, by = NULL) ## S3 method for class 'SpatRaster' slice_min( .data, order_by, ..., n, prop, with_ties = TRUE, .keep_extent = FALSE, na.rm = TRUE ) ## S3 method for class 'SpatVector' slice_min( .data, order_by, ..., n, prop, by = NULL, with_ties = TRUE, na_rm = FALSE ) ## S3 method for class 'SpatRaster' slice_max( .data, order_by, ..., n, prop, with_ties = TRUE, .keep_extent = FALSE, na.rm = TRUE ) ## S3 method for class 'SpatVector' slice_max( .data, order_by, ..., n, prop, by = NULL, with_ties = TRUE, na_rm = FALSE ) ## S3 method for class 'SpatRaster' slice_sample( .data, ..., n, prop, weight_by = NULL, replace = FALSE, .keep_extent = FALSE ) ## S3 method for class 'SpatVector' slice_sample(.data, ..., n, prop, by = NULL, weight_by = NULL, replace = FALSE) slice_rows(.data, ...) ## S3 method for class 'SpatRaster' slice_rows(.data, ..., .keep_extent = FALSE) slice_cols(.data, ...) ## S3 method for class 'SpatRaster' slice_cols(.data, ..., .keep_extent = FALSE) slice_colrows(.data, ...) ## S3 method for class 'SpatRaster' slice_colrows(.data, ..., cols, rows, .keep_extent = FALSE, inverse = FALSE)## S3 method for class 'SpatRaster' slice(.data, ..., .preserve = FALSE, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice(.data, ..., .by = NULL, .preserve = FALSE) ## S3 method for class 'SpatRaster' slice_head(.data, ..., n, prop, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice_head(.data, ..., n, prop, by = NULL) ## S3 method for class 'SpatRaster' slice_tail(.data, ..., n, prop, .keep_extent = FALSE) ## S3 method for class 'SpatVector' slice_tail(.data, ..., n, prop, by = NULL) ## S3 method for class 'SpatRaster' slice_min( .data, order_by, ..., n, prop, with_ties = TRUE, .keep_extent = FALSE, na.rm = TRUE ) ## S3 method for class 'SpatVector' slice_min( .data, order_by, ..., n, prop, by = NULL, with_ties = TRUE, na_rm = FALSE ) ## S3 method for class 'SpatRaster' slice_max( .data, order_by, ..., n, prop, with_ties = TRUE, .keep_extent = FALSE, na.rm = TRUE ) ## S3 method for class 'SpatVector' slice_max( .data, order_by, ..., n, prop, by = NULL, with_ties = TRUE, na_rm = FALSE ) ## S3 method for class 'SpatRaster' slice_sample( .data, ..., n, prop, weight_by = NULL, replace = FALSE, .keep_extent = FALSE ) ## S3 method for class 'SpatVector' slice_sample(.data, ..., n, prop, by = NULL, weight_by = NULL, replace = FALSE) slice_rows(.data, ...) ## S3 method for class 'SpatRaster' slice_rows(.data, ..., .keep_extent = FALSE) slice_cols(.data, ...) ## S3 method for class 'SpatRaster' slice_cols(.data, ..., .keep_extent = FALSE) slice_colrows(.data, ...) ## S3 method for class 'SpatRaster' slice_colrows(.data, ..., cols, rows, .keep_extent = FALSE, inverse = FALSE)
.data |
A |
... |
< The values provided must be either all positive or all negative. Indices beyond the number of rows in the input are silently ignored. See Methods. |
.preserve |
Ignored for |
.keep_extent |
Logical. If |
.by, by
|
< |
n, prop
|
Provide either A negative value of |
order_by |
< |
with_ties |
Should ties be kept together? The default, |
na.rm |
Logical. If |
na_rm |
Should missing values in |
weight_by |
< |
replace |
Should sampling be performed with ( |
cols, rows
|
Integer column and row values of the |
inverse |
If |
A Spat* object of the same class as .data. See Methods.
terra::subset(), terra::spatSample()
Implementation of the generic dplyr::slice() method.
SpatRasterThe result is a SpatRaster with the CRS and resolution of the input and
where cell values of the selected cells/columns/rows are preserved.
Use .keep_extent = TRUE to preserve the extent of .data on the output.
The non-selected cells have a value of NA.
SpatVectorThe result is a SpatVector where the attributes of the selected
geometries are preserved. If .data is a
grouped SpatVector, the operation will be
performed on each group, so that (e.g.) slice_head(df, n = 5) will select
the first five rows in each group.
dplyr::slice(), terra::spatSample(), as_coordinates(),
filter.SpatRaster().
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
mutate.Spat,
reframe.SpatVector(),
rename.Spat,
select.Spat,
summarise.SpatVector()
Other dplyr verbs that operate on rows:
arrange.SpatVector(),
distinct.SpatVector(),
filter.Spat,
rows.SpatVector
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
summarise.SpatVector()
library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) # Slice first 100 cells r |> slice(1:100) |> plot() # Rows r |> slice_rows(1:30) |> plot() # Cols r |> slice_cols(-(20:50)) |> plot() # Spatial sample r |> slice_sample(prop = 0.2) |> plot() # Slice regions r |> slice_colrows( cols = c(20:40, 60:80), rows = -c(1:20, 30:50) ) |> plot() # Group wise operation with SpatVectors-------------------------------------- v <- terra::vect(system.file("ex/lux.shp", package = "terra")) glimpse(v) |> autoplot(aes(fill = NAME_1)) gv <- v |> group_by(NAME_1) # All slice helpers operate per group, silently truncating to the group size gv |> slice_head(n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_tail(n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_min(AREA, n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_max(AREA, n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1))library(terra) f <- system.file("extdata/cyl_temp.tif", package = "tidyterra") r <- rast(f) # Slice first 100 cells r |> slice(1:100) |> plot() # Rows r |> slice_rows(1:30) |> plot() # Cols r |> slice_cols(-(20:50)) |> plot() # Spatial sample r |> slice_sample(prop = 0.2) |> plot() # Slice regions r |> slice_colrows( cols = c(20:40, 60:80), rows = -c(1:20, 30:50) ) |> plot() # Group wise operation with SpatVectors-------------------------------------- v <- terra::vect(system.file("ex/lux.shp", package = "terra")) glimpse(v) |> autoplot(aes(fill = NAME_1)) gv <- v |> group_by(NAME_1) # All slice helpers operate per group, silently truncating to the group size gv |> slice_head(n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_tail(n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_min(AREA, n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1)) gv |> slice_max(AREA, n = 1) |> glimpse() |> autoplot(aes(fill = NAME_1))
SpatVector down to one geometrysummarise() creates a new SpatVector. It returns one geometry for each
combination of grouping variables. If there are no grouping variables, the
output will have a single geometry summarising all observations in the input
and combining all the geometries of the SpatVector. It will contain one
column for each grouping variable and one column for each of
the summary statistics that you have specified.
summarise.SpatVector() and summarize.SpatVector() are synonyms
## S3 method for class 'SpatVector' summarise(.data, ..., .by = NULL, .groups = NULL, .dissolve = TRUE) ## S3 method for class 'SpatVector' summarize(.data, ..., .by = NULL, .groups = NULL, .dissolve = TRUE)## S3 method for class 'SpatVector' summarise(.data, ..., .by = NULL, .groups = NULL, .dissolve = TRUE) ## S3 method for class 'SpatVector' summarize(.data, ..., .by = NULL, .groups = NULL, .dissolve = TRUE)
.data |
A |
... |
< The value can be:
|
.by |
< |
.groups |
When |
.dissolve |
Logical. If |
A SpatVector.
Implementation of the generic dplyr::summarise() method.
SpatVectorSimilarly to the implementation on sf this function can be used to
dissolve geometries (with .dissolve = TRUE) or create MULTI versions of
geometries (with .dissolve = FALSE). See Examples.
dplyr::summarise(), terra::aggregate()
Other single table verbs:
arrange.SpatVector(),
filter.Spat,
mutate.Spat,
reframe.SpatVector(),
rename.Spat,
select.Spat,
slice.Spat
Other dplyr verbs that operate on group of rows:
count.SpatVector(),
group_by.SpatVector(),
reframe.SpatVector(),
rowwise.SpatVector()
Other dplyr methods:
arrange.SpatVector(),
bind_cols.SpatVector,
bind_rows.SpatVector,
count.SpatVector(),
cross_join.SpatVector(),
distinct.SpatVector(),
filter-joins.SpatVector,
filter.Spat,
glimpse.Spat,
group_by.SpatVector(),
mutate-joins.SpatVector,
mutate.Spat,
nest_join.SpatVector(),
pull.Spat,
reframe.SpatVector(),
relocate.Spat,
rename.Spat,
rows.SpatVector,
rowwise.SpatVector(),
select.Spat,
slice.Spat
library(terra) library(ggplot2) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Grouped gr_v <- v |> mutate(start_with_s = startsWith(name, "S")) |> group_by(start_with_s) # Dissolving diss <- gr_v |> summarise(n = dplyr::n(), mean = mean(as.double(cpro))) diss autoplot(diss, aes(fill = start_with_s)) + ggplot2::labs(title = "Dissolved") # Not dissolving no_diss <- gr_v |> summarise(n = dplyr::n(), mean = mean(as.double(cpro)), .dissolve = FALSE) # Same statistic no_diss autoplot(no_diss, aes(fill = start_with_s)) + ggplot2::labs(title = "Not Dissolved")library(terra) library(ggplot2) v <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) # Grouped gr_v <- v |> mutate(start_with_s = startsWith(name, "S")) |> group_by(start_with_s) # Dissolving diss <- gr_v |> summarise(n = dplyr::n(), mean = mean(as.double(cpro))) diss autoplot(diss, aes(fill = start_with_s)) + ggplot2::labs(title = "Dissolved") # Not dissolving no_diss <- gr_v |> summarise(n = dplyr::n(), mean = mean(as.double(cpro)), .dissolve = FALSE) # Same statistic no_diss autoplot(no_diss, aes(fill = start_with_s)) + ggplot2::labs(title = "Not Dissolved")
Spat* objects for plottingtidy() methods for SpatRaster, SpatVector, SpatGraticule and
SpatExtent objects. These methods return a tibble for SpatRaster
objects and sf objects for vector-based inputs. This interface is similar
to fortify.Spat and is provided in case the ggplot2::fortify() method
is deprecated in the future.
## S3 method for class 'SpatRaster' tidy( x, ..., .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet"), maxcell = terra::ncell(x) * 1.1, pivot = FALSE ) ## S3 method for class 'SpatVector' tidy(x, ...) ## S3 method for class 'SpatGraticule' tidy(x, ...) ## S3 method for class 'SpatExtent' tidy(x, ..., crs = "")## S3 method for class 'SpatRaster' tidy( x, ..., .name_repair = c("unique", "check_unique", "universal", "minimal", "unique_quiet", "universal_quiet"), maxcell = terra::ncell(x) * 1.1, pivot = FALSE ) ## S3 method for class 'SpatVector' tidy(x, ...) ## S3 method for class 'SpatGraticule' tidy(x, ...) ## S3 method for class 'SpatExtent' tidy(x, ..., crs = "")
x |
A |
... |
Ignored by these methods. |
.name_repair |
Treatment of problematic column names:
This argument is passed on as |
maxcell |
Positive integer. Maximum number of cells to use for the plot. |
pivot |
Logical. When |
crs |
Input that includes or represents a CRS. It can be an |
tidy.SpatVector(), tidy.SpatGraticule() and tidy.SpatExtent()
return a sf object.
tidy.SpatRaster() returns a tibble. See Methods.
Implementation of the generic generics::tidy() method.
SpatRasterReturns a tibble that can be used with ggplot2::geom_*, such as
ggplot2::geom_point() and ggplot2::geom_raster().
The resulting tibble includes coordinates in the x and y columns. The
values of each layer are added as extra columns using the layer names from
the SpatRaster.
The CRS of the SpatRaster can be retrieved with
attr(tidySpatRaster, "crs").
You can convert the tidy object back to a SpatRaster with
as_spatraster().
When pivot = TRUE, the SpatRaster is returned in long format (see
tidyr::pivot_longer()). The tidy object has the following columns:
x, y: Coordinates of the cell center in the corresponding CRS.
lyr: Name of the SpatRaster layer associated with value.
value: Cell value for the corresponding lyr.
This option can be useful when combining several geom_* layers or when
faceting.
SpatVector, SpatGraticule and SpatExtent
Returns an sf object that can be used with
ggplot2::geom_sf().
sf::st_as_sf(), as_tibble.Spat, as_spatraster(), fortify.Spat,
generics::tidy().
Other generics methods:
glance.Spat,
required_pkgs.Spat
Coercing objects:
as_coordinates(),
as_sf(),
as_spatraster(),
as_spatvector(),
as_tibble.Spat,
fortify.Spat
# Get a SpatRaster r <- system.file("extdata/volcano2.tif", package = "tidyterra") |> terra::rast() |> terra::project("EPSG:4326") r_tidy <- tidy(r) r_tidy # Convert back to a `SpatRaster`. as_spatraster(r_tidy) # SpatVector cyl <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) cyl tidy(cyl) # SpatExtent ex <- cyl |> terra::ext() ex tidy(ex) # With crs tidy(ex, crs = pull_crs(cyl)) # SpatGraticule grat <- terra::graticule(60, 30, crs = "+proj=robin") grat tidy(grat)# Get a SpatRaster r <- system.file("extdata/volcano2.tif", package = "tidyterra") |> terra::rast() |> terra::project("EPSG:4326") r_tidy <- tidy(r) r_tidy # Convert back to a `SpatRaster`. as_spatraster(r_tidy) # SpatVector cyl <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) cyl tidy(cyl) # SpatExtent ex <- cyl |> terra::ext() ex tidy(ex) # With crs tidy(ex, crs = pull_crs(cyl)) # SpatGraticule grat <- terra::graticule(60, 30, crs = "+proj=robin") grat tidy(grat)
SpatVector rowsuncount() duplicates rows according to a weighting variable.
## S3 method for class 'SpatVector' uncount(data, weights, ..., .remove = TRUE, .id = NULL)## S3 method for class 'SpatVector' uncount(data, weights, ..., .remove = TRUE, .id = NULL)
data |
A |
weights |
A vector of weights. Evaluated in the context of |
... |
Additional arguments passed on to methods. |
.remove |
If |
.id |
Supply a string to create a new variable which gives a unique identifier for each created row. |
A SpatVector object.
Implementation of the generic tidyr::uncount() method.
SpatVectorEach duplicated row keeps the geometry of the input feature.
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
unite.Spat
library(tidyr) v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$copies <- rep_len(1:2, nrow(v)) uncount(v, copies)library(tidyr) v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) v$copies <- rep_len(1:2, nrow(v)) uncount(v, copies)
Spat* layers or attributesunite() combines multiple layers or attributes by pasting their values
together.
## S3 method for class 'SpatRaster' unite(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE) ## S3 method for class 'SpatVector' unite(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE)## S3 method for class 'SpatRaster' unite(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE) ## S3 method for class 'SpatVector' unite(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE)
data |
A |
col |
The name of the new column, as a string or symbol. This argument is passed by expression and supports
quasiquotation (you can unquote strings
and symbols). The name is captured from the expression with
|
... |
< |
sep |
Separator to use between values. |
remove |
If |
na.rm |
If |
A SpatRaster or SpatVector object.
Implementation of the generic tidyr::unite() method.
SpatRasterThe selected layers are united cell by cell. The new layer is categorical
because tidyr::unite() returns a character vector.
SpatVectorThe geometry column has sticky behavior and is never united with attributes.
Other tidyr methods:
complete.SpatVector(),
drop_na.Spat,
expand.SpatVector(),
fill.SpatVector(),
nest.SpatVector(),
pivot_longer.SpatVector(),
pivot_wider.SpatVector(),
replace_na.Spat,
uncount.SpatVector()
library(tidyr) v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) unite(v, "label", iso2, cpro, sep = "-") r <- terra::rast(system.file("extdata/cyl_temp.tif", package = "tidyterra")) unite(r, "label", tavg_04, tavg_05, sep = "-", remove = FALSE)library(tidyr) v <- terra::vect(system.file("extdata/cyl.gpkg", package = "tidyterra")) unite(v, "label", iso2, cpro, sep = "-") r <- terra::rast(system.file("extdata/cyl_temp.tif", package = "tidyterra")) unite(r, "label", tavg_04, tavg_05, sep = "-", remove = FALSE)
Probably you already know the volcano dataset. This dataset provides updated information of Maungawhau (Mt. Eden) from Toitu Te Whenua Land Information New Zealand, the Government's agency that provides free online access to New Zealand's most up-to-date land and seabed data.
A matrix of 174 rows and 122 columns. Each value is the corresponding altitude in meters.
Information needed for regenerating the original SpatRaster file:
resolution: c(5, 5)
extent: 1756969, 1757579, 5917003, 5917873 (xmin, xmax, ymin, ymax)
Coordinate reference system: NZGD2000 / New Zealand Transverse Mercator
2000 (EPSG:2193)
DEM for LiDAR data from the Auckland region captured in 2013. The original data has been downsampled to a resolution of 5 m due to disk space constraints.
Data License: CC BY 4.0.
Other datasets:
cross_blended_hypsometric_tints_db,
grass_db,
hypsometric_tints_db,
princess_db
data("volcano2") filled.contour(volcano2, color.palette = hypso.colors, asp = 1) title(main = "volcano2 data: filled contour map") # Geo-tag # Empty raster volcano2_raster <- terra::rast(volcano2) terra::crs(volcano2_raster) <- pull_crs(2193) terra::ext(volcano2_raster) <- c(1756968, 1757576, 5917000, 5917872) names(volcano2_raster) <- "volcano2" library(ggplot2) ggplot() + geom_spatraster(data = volcano2_raster) + scale_fill_hypso_c() + labs( title = "volcano2 SpatRaster", subtitle = "Georeferenced", fill = "Elevation (m)" )data("volcano2") filled.contour(volcano2, color.palette = hypso.colors, asp = 1) title(main = "volcano2 data: filled contour map") # Geo-tag # Empty raster volcano2_raster <- terra::rast(volcano2) terra::crs(volcano2_raster) <- pull_crs(2193) terra::ext(volcano2_raster) <- c(1756968, 1757576, 5917000, 5917872) names(volcano2_raster) <- "volcano2" library(ggplot2) ggplot() + geom_spatraster(data = volcano2_raster) + scale_fill_hypso_c() + labs( title = "volcano2 SpatRaster", subtitle = "Georeferenced", fill = "Elevation (m)" )