Skip to contents

Fortify SpatRasters and SpatVectors to data frames for compatibility with ggplot2::ggplot().

Usage

# S3 method for SpatRaster
fortify(
  model,
  data,
  ...,
  .name_repair = "unique",
  maxcell = terra::ncell(model) * 1.1
)

# S3 method for SpatVector
fortify(model, data, ...)

Arguments

model

A SpatRaster created with terra::rast() or a SpatVector created with terra::vect().

data

Not used by this method.

...

other arguments passed to methods

.name_repair

Treatment of problematic column names:

  • "minimal": No name repair or checks, beyond basic existence,

  • "unique": Make sure names are unique and not empty,

  • "check_unique": (default value), no name repair, but check they are unique,

  • "universal": Make the names unique and syntactic

  • a function: apply custom name repair (e.g., .name_repair = make.names for names in the style of base R).

  • A purrr-style anonymous function, see rlang::as_function()

maxcell

positive integer. Maximum number of cells to use for the plot.

Value

fortify.SpatVector() returns a sf object and fortify.SpatRaster() returns a tibble. See Methods.

Methods

Implementation of the generic ggplot2::fortify() function.

SpatRaster

Return a tibble than 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").

It is possible to convert the fortified object onto a SpatRaster again with as_spatraster().

SpatVector

Return a sf object than can be used with ggplot2::geom_sf().

Examples

# \donttest{

# Get a SpatRaster
r <- system.file("extdata/volcano2.tif", package = "tidyterra") %>%
  terra::rast()

fortified <- ggplot2::fortify(r)

fortified
#> # A tibble: 21,228 × 3
#>           x        y elevation
#>       <dbl>    <dbl>     <dbl>
#>  1 1756972. 5917870.      80.6
#>  2 1756976. 5917870.      80.4
#>  3 1756982. 5917870.      80.5
#>  4 1756986. 5917870.      80.6
#>  5 1756992. 5917870.      81.2
#>  6 1756996. 5917870.      81.5
#>  7 1757002. 5917870.      81.3
#>  8 1757006. 5917870.      80.9
#>  9 1757012. 5917870.      79.8
#> 10 1757016. 5917870.      77.8
#> # … with 21,218 more rows

# The crs is an attribute of the fortified SpatRaster

attr(fortified, "crs")
#> [1] "PROJCRS[\"NZGD2000 / New Zealand Transverse Mercator 2000\",\n    BASEGEOGCRS[\"NZGD2000\",\n        DATUM[\"New Zealand Geodetic Datum 2000\",\n            ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n                LENGTHUNIT[\"metre\",1]]],\n        PRIMEM[\"Greenwich\",0,\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        ID[\"EPSG\",4167]],\n    CONVERSION[\"New Zealand Transverse Mercator 2000\",\n        METHOD[\"Transverse Mercator\",\n            ID[\"EPSG\",9807]],\n        PARAMETER[\"Latitude of natural origin\",0,\n            ANGLEUNIT[\"degree\",0.0174532925199433],\n            ID[\"EPSG\",8801]],\n        PARAMETER[\"Longitude of natural origin\",173,\n            ANGLEUNIT[\"degree\",0.0174532925199433],\n            ID[\"EPSG\",8802]],\n        PARAMETER[\"Scale factor at natural origin\",0.9996,\n            SCALEUNIT[\"unity\",1],\n            ID[\"EPSG\",8805]],\n        PARAMETER[\"False easting\",1600000,\n            LENGTHUNIT[\"metre\",1],\n            ID[\"EPSG\",8806]],\n        PARAMETER[\"False northing\",10000000,\n            LENGTHUNIT[\"metre\",1],\n            ID[\"EPSG\",8807]]],\n    CS[Cartesian,2],\n        AXIS[\"northing (N)\",north,\n            ORDER[1],\n            LENGTHUNIT[\"metre\",1]],\n        AXIS[\"easting (E)\",east,\n            ORDER[2],\n            LENGTHUNIT[\"metre\",1]],\n    USAGE[\n        SCOPE[\"Engineering survey, topographic mapping.\"],\n        AREA[\"New Zealand - North Island, South Island, Stewart Island - onshore.\"],\n        BBOX[-47.33,166.37,-34.1,178.63]],\n    ID[\"EPSG\",2193]]"

# Back to a SpatRaster with
as_spatraster(fortified)
#> class       : SpatRaster 
#> dimensions  : 174, 122, 1  (nrow, ncol, nlyr)
#> resolution  : 5, 5  (x, y)
#> extent      : 1756969, 1757579, 5917003, 5917873  (xmin, xmax, ymin, ymax)
#> coord. ref. : NZGD2000 / New Zealand Transverse Mercator 2000 (EPSG:2193) 
#> source(s)   : memory
#> name        : elevation 
#> min value   :  76.26222 
#> max value   : 195.55420 

# You can now use a SpatRaster with raster, contours, etc.
library(ggplot2)

# Use here the raster with resample
ggplot(r, maxcell = 10000) +
  # Need the aes parameters
  geom_raster(aes(x, y, fill = elevation)) +
  # Adjust the coords
  coord_equal()
#> SpatRaster resampled to ncells = 10080


# Or any other geom
ggplot(r) +
  geom_histogram(aes(x = elevation),
    bins = 20, fill = "lightblue",
    color = "black"
  )


# Create a SpatVector
extfile <- system.file("extdata/cyl.gpkg", package = "tidyterra")
cyl <- terra::vect(extfile)

cyl
#>  class       : SpatVector 
#>  geometry    : polygons 
#>  dimensions  : 9, 3  (geometries, attributes)
#>  extent      : 2892687, 3341372, 2017622, 2361600  (xmin, xmax, ymin, ymax)
#>  source      : cyl.gpkg
#>  coord. ref. : ETRS89-extended / LAEA Europe (EPSG:3035) 
#>  names       :  iso2  cpro   name
#>  type        : <chr> <chr>  <chr>
#>  values      : ES-AV    05  Avila
#>                ES-BU    09 Burgos
#>                ES-LE    24   Leon

# To sf
ggplot2::fortify(cyl)
#> Simple feature collection with 9 features and 3 fields
#> Geometry type: GEOMETRY
#> Dimension:     XY
#> Bounding box:  xmin: 2892687 ymin: 2017622 xmax: 3341372 ymax: 2361600
#> Projected CRS: ETRS89-extended / LAEA Europe
#>    iso2 cpro       name                       geometry
#> 1 ES-AV   05      Avila POLYGON ((3126360 2066778, ...
#> 2 ES-BU   09     Burgos MULTIPOLYGON (((3276731 226...
#> 3 ES-LE   24       Leon POLYGON ((3049427 2233673, ...
#> 4  ES-P   34   Palencia MULTIPOLYGON (((3175411 229...
#> 5 ES-SA   37  Salamanca POLYGON ((3042661 2138939, ...
#> 6 ES-SG   40    Segovia POLYGON ((3126360 2066778, ...
#> 7 ES-SO   42      Soria POLYGON ((3194084 2154251, ...
#> 8 ES-VA   47 Valladolid MULTIPOLYGON (((3158120 216...
#> 9 ES-ZA   49     Zamora POLYGON ((3042661 2138939, ...

# Now you can use geom_sf()

library(ggplot2)

ggplot(cyl) +
  geom_sf()

# }