tidyterra

repository·main·Indexed 42 days ago

https://github.com/dieghernan/tidyterra

An R package providing tidyverse-style methods (dplyr, tidyr) and ggplot2 extensions (geoms, scales) for SpatRaster and SpatVector objects created with the terra package. It includes specialized tools such as geom_spatraster(), geom_spatraster_rgb(), and hypsometric scales like scale_fill_hypso_tint_c() for spatial data visualization.

Tokens
3K
Snippets
7
Records
11
Agent score
3%

What's inside tidyterra

  1. Performance considerations for tidyterra

    main

    Because tidyterra acts as a user-friendly wrapper around terra to provide tidyverse-style verbs, there is a performance cost compared to using terra directly.

    Recommendation:

    • Use terra directly for maximum speed, especially with very large datasets.
    • Use tidyterra when your raster has fewer than 10,000,000 data slots. A good rule of thumb is: terra::ncell(your_rast) * terra::nlyr(your_rast) < 1e7.

    When plotting rasters, tidyterra performs automatic resampling (similar to terra::plot()). You can control this behavior using the maxcell argument.

  2. How tidyterra handles SpatVector and SpatRaster objects

    main

    The tidyterra package provides tidyverse methods for terra objects. The implementation logic differs based on the object type:

    • SpatVector: Methods use terra::as.data.frame() coercion. Each row corresponds to a geometry, and columns correspond to the attributes of that geometry.
    • SpatRaster: Methods treat layers as columns of a tibble and cells as rows. For example, dplyr::select(a_spatraster, 1) selects the first layer.

    Implemented methods generally return the same type of object as the input (e.g., a SpatRaster remains a SpatRaster), unless the method is explicitly designed to return a different type, such as as_tibble() returning a tibble.

  3. How tidyterra handles SpatRaster and SpatVector objects

    main

    tidyterra provides tidyverse-style methods for terra objects. The implementation logic differs based on the object type:

    • SpatVector: Methods use terra::as.data.frame() coercion. Each row represents a geometry, and columns represent attributes.
    • SpatRaster: Methods treat layers as columns of a tibble and cells as rows. For example, dplyr::select(a_spatraster, 1) selects the first layer.

    Implemented methods generally return the same type of object as the input (e.g., as_tibble() returns a tibble), unless the method is explicitly designed to change the type.

    Performance Note

    tidyterra is a wrapper around terra, which introduces a performance cost. For very large datasets, use terra directly. A rule of thumb is to use tidyterra if your raster has fewer than 10,000,000 data slots (terra::ncell(your_rast) * terra::nlyr(your_rast) < 1e7).

  4. Install tidyterra

    main

    You can install tidyterra from CRAN using the standard install.packages() function. If you want to use the development version, you can use pak or install it via r-universe.

    Install from CRAN

    install.packages("tidyterra")

    Install development version via pak

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

    Install via r-universe

    install.packages(
      "tidyterra",
      repos = c(
        "https://dieghernan.r-universe.dev",
        "https://cloud.r-project.org"
      )
    )
    install.packages("tidyterra")
  5. Plotting SpatRaster objects with ggplot2

    main

    tidyterra provides specialized geoms and scales for plotting SpatRaster objects in ggplot2.

    Basic Raster Plotting

    Use geom_spatraster() to plot a SpatRaster.

    RGB Raster Plotting

    For RGB SpatRaster objects (like map tiles), use geom_spatraster_rgb().

    Hypsometric Tints

    Use scale_fill_hypso_tint_c() to create maps with hypsometric tints (elevation-based color scales).

    Example: Manipulating and Faceting Rasters

    library(tidyterra)
    library(terra)
    library(ggplot2)
    
    # Load raster
    rastertemp <- rast(system.file("extdata/cyl_temp.tif", package = "tidyterra"))
    
    # Rename layers and plot with facets
    rastertemp |> 
      rename(April = tavg_04, May = tavg_05, June = tavg_06) |>
      ggplot() +
        geom_spatraster(data = .) +
        facet_wrap(~lyr, ncol = 2) +
        scale_fill_whitebox_c(palette = "muted")
    ggplot() +
      geom_spatraster(data = rastertemp) + 
      facet_wrap(~lyr, ncol = 2)
  6. Plot SpatVector objects with autoplot()

    main

    You can manipulate SpatVector objects using tidyverse-style verbs like mutate() and then plot them directly using autoplot(). This integrates seamlessly with ggplot2 scales and labels.

    library(tidyterra)
    library(terra)
    library(ggplot2)
    
    # Manipulate SpatVector and plot
    vect(system.file("ex/lux.shp", package = "terra")) |>
      mutate(pop_dens = POP / AREA) |>
      autoplot(aes(fill = pop_dens)) +
      scale_fill_whitebox_c(palette = "pi_y_g") +
      labs(
        fill = "population per km2",
        title = "Population density of Luxembourg",
        subtitle = "By canton"
      )
  7. Use Whitebox and Hypsometric scales for SpatRaster

    main

    The tidyterra package provides specialized scales for mapping:

    1. Whitebox scales: Use scale_fill_whitebox_c() for continuous data. It supports various palettes (e.g., "muted", "deep") and allows for custom labels and guides.
    2. Hypsometric scales: Use scale_fill_hypso_tint_c() to create maps with hypsometric tints (elevation-based color schemes). This is ideal for topographic maps.

    Example of a hypsometric map:

    # Hypsometric map example
    ها <- rast(system.file("extdata/asia.tif", package = "tidyterra"))
    
    ggplot() +
      geom_spatraster(data = asia) +
      scale_fill_hypso_tint_c(
        palette = "gmt_globe",
        labels = scales::label_number(),
        breaks = c(-10000, -5000, 0, 2000, 5000, 8000),
        guide = guide_colorbar(reverse = TRUE)
      ) +
      labs(fill = "elevation (m)", title = "Hypsometric map of Asia")
  8. Plot SpatRaster objects with ggplot2

    main

    Use geom_spatraster() to plot SpatRaster objects within a ggplot2 workflow. You can facet across multiple layers using facet_wrap(~lyr, ...) to visualize different time steps or variables in a single plot.

    To plot RGB SpatRaster objects (like map tiles), use geom_spatraster_rgb() instead.

    library(tidyterra)
    library(terra)
    library(ggplot2)
    
    # Load a SpatRaster
    rastertemp <- rast(system.file("extdata/cyl_temp.tif", package = "tidyterra"))
    
    # Plotting all layers faceted
    ggplot() +
      geom_spatraster(data = rastertemp) +
      facet_wrap(~lyr, ncol = 2)
  9. Reference of tidyverse methods implemented in tidyterra

    main

    The following table lists the tidyverse methods implemented for SpatVector and SpatRaster objects. Note that some methods have specific behaviors (e.g., dplyr::select selects layers for rasters, and tidyr::drop_na can remove outer cells).

    | **tidyverse** method | `SpatVector` | `SpatRaster` |
    |----|----|----|
    | `tibble::as_tibble()` | ✔️ | ✔️ |
    | `dplyr::select()` | ✔️ | ✔️ Select layers |
    | `dplyr::mutate()` | ✔️ | ✔️ Create or modify layers |
    | `dplyr::transmute()` | ✔️ | ✔️ |
    | `dplyr::filter()` | ✔️ | ✔️ Modify cell values and optionally remove outer cells. |
    | `dplyr::filter_out()` | ✔️ |  |
    | `dplyr::slice()` | ✔️ | ✔️ Additional methods for slicing by row and column. |
    | `dplyr::pull()` | ✔️ | ✔️ |
    | `dplyr::rename()` | ✔️ | ✔️ |
    | `dplyr::relocate()` | ✔️ | ✔️ |
    | `dplyr::distinct()` | ✔️ |  |
    | `dplyr::arrange()` | ✔️ |  |
    | `dplyr::glimpse()` | ✔️ | ✔️ |
    | `dplyr::inner_join()` family | ✔️ |  |
    | `dplyr::nest_join()` | ✔️ |  |
    | `dplyr::cross_join()` | ✔️ |  |
    | `dplyr::summarise()` | ✔️ |  |
    | `dplyr::reframe()` | ✔️ |  |
    | `dplyr::group_by()` family | ✔️ |  |
    | `dplyr::rowwise()` | ✔️ |  |
    | `dplyr::count()`, `tally()` | ✔️ |  |
    | `dplyr::add_count()` | ✔️ |  |
    | `dplyr::rows_*()` | ✔️ |  |
    | `dplyr::bind_cols()` / `dplyr::bind_rows()` | ✔️ as `bind_spat_cols()` / `bind_spat_rows()` |  |
    | `tidyr::drop_na()` | ✔️ | ✔️ Remove cell values with `NA` on any layer and outer cells with `NA`. |
    | `tidyr::complete()` | ✔️ |  |
    | `tidyr::expand()` | ✔️ |  |
    | `tidyr::replace_na()` | ✔️ | ✔️ |
    | `tidyr::fill()` | ✔️ |  |
    | `tidyr::nest()` | ✔️ |  |
    | `tidyr::pivot_longer()` | ✔️ |  |
    | `tidyr::pivot_wider()` | ✔️ |  |
    | `tidyr::uncount()` | ✔️ |  |
    | `tidyr::unite()` | ✔️ | ✔️ Create a categorical layer. |
    | `ggplot2::autoplot()` | ✔️ | ✔️ |
    | `ggplot2::fortify()` | ✔️ to **sf** through `sf::st_as_sf()` | To a **tibble** with coordinates. |
    | `ggplot2::geom_*()` | ✔️ `geom_spatvector()` | ✔️ `geom_spatraster()` and `geom_spatraster_rgb()` |
    | `generics::tidy()` | ✔️ | ✔️ |
    | `generics::glance()` | ✔️ | ✔️ |
    | `generics::required_pkgs()` | ✔️ | ✔️ |
  10. Plotting SpatVector objects with ggplot2

    main

    tidyterra allows you to use tidyverse verbs on SpatVector objects and plot them using ggplot2 via autoplot() or geom_spatvector().

    Example: Mutate and Plot SpatVector

    library(tidyterra)
    library(terra)
    
    # Create a SpatVector, mutate attributes, and plot
    vect(system.file("ex/lux.shp", package = "terra")) |>
      mutate(pop_dens = POP / AREA) |>
      glimpse() |>
      autoplot(aes(fill = pop_dens)) +
      scale_fill_whitebox_c(palette = "pi_y_g")
    vect(system.file("ex/lux.shp", package = "terra")) |>
      mutate(pop_dens = POP / AREA) |>
      glimpse() |>
      autoplot(aes(fill = pop_dens))
  11. Tidyterra supported tidyverse methods

    main

    tidyterra implements a wide range of tidyverse methods for both SpatVector and SpatRaster objects.

    tidyverse methodSpatVectorSpatRaster
    tibble::as_tibble()✔️✔️
    dplyr::select()✔️✔️ Select layers
    dplyr::mutate()✔️✔️ Create or modify layers
    dplyr::filter()✔️✔️ Modify cell values
    dplyr::rename()✔️✔️
    tidyr::drop_na()✔️✔️
    tidyr::replace_na()✔️✔️
    ggplot2::autoplot()✔️✔️
    ggplot2::geom_spatvector()✔️N/A
    ggplot2::geom_spatraster()N/A✔️
    ggplot2::geom_spatraster_rgb()N/A✔️
    generics::tidy()✔️✔️