This article collects frequently asked questions about using tidyterra, with a focus on the integration of terra and ggplot2. You can ask for help or search existing questions using the following links.
Can I ask questions about tidyterra documentation?
The experimental tidyterra AI assistant answers questions using the development documentation. Open the chat button in the lower-right corner of the documentation website. You can ask in your preferred language and include the type of spatial object, the function you are using and what you want to do.
Each answer can include a Sources consulted dropdown linking to the documentation retrieved for that question. Open these sources to check the answer. Code blocks have a Copy code button.
The assistant can give incorrect answers or examples and does not execute R code. Check generated code before using it. Questions are sent to Cloudflare for processing, so avoid including private data. You can also use the FAQs, site search or community support links above.
NA values are shown in gray
This is the default behavior of ggplot2. tidyterra color scales, such as scale_fill_whitebox_c(), have na.value = "transparent" by default, which prevents NA values from being filled2.
library(terra)library(tidyterra)library(ggplot2)# Get raster data from Holyrood Park, Edinburgh.holyrood<-"holyroodpark.tif"r<-holyrood|>rast()|>filter(elevation>80&elevation<180)# Default behavior.def<-ggplot()+geom_spatraster(data =r)def+labs( title ="Default in ggplot2", subtitle ="NA values in gray")# Modify with scales.def+scale_fill_continuous(na.value ="transparent")+labs( title ="Default colors in ggplot2", subtitle ="But NA values are not plotted")# Use a different scale provided by ggplot2.def+scale_fill_viridis_c(na.value ="orange")+labs( title ="Use any ggplot2 fill scale", subtitle ="na.value = 'orange'")
Figure 5: Changing default ggplot2 color palettes.
My map tiles are blurry
Blurriness is typically related to the tile source rather than the package.
Important
Most base tiles are usually provided in EPSG:3857, so verify that your tile uses this CRS rather than a different one. If your tile is not in EPSG:3857, it has likely been reprojected, which involves resampling and causes blurriness. To avoid extra resampling, increase the maxcell argument and ensure the ggplot2 map uses EPSG:3857 with ggplot2::coord_sf(crs = 3857).
We omitted the legends in this section’s figures to improve readability.
tidyterra provides several methods for handling SpatRaster objects with color tables. This example uses clc_edinburgh.tif, available online in the data-raw folder. It contains data from the CORINE Land Cover dataset (2018) for Edinburgh3.
library(terra)library(tidyterra)library(ggplot2)# Get a SpatRaster with a color table.r_coltab<-rast("clc_edinburgh.tif")has.colors(r_coltab)#> [1] TRUEr_coltab#> class : SpatRaster#> size : 196, 311, 1 (nrow, ncol, nlyr)#> resolution : 178.8719, 177.9949 (x, y)#> extent : -380397.3, -324768.1, 7533021, 7567908 (xmin, xmax, ymin, ymax)#> coord. ref. : WGS 84 / Pseudo-Mercator (EPSG:3857)#> source : clc_edinburgh.tif#> color table : 1#> categories : label#> name : label#> min value : Continuous urban fabric#> max value : Sea and ocean# Native handling by terra.plot(r_coltab, legend =FALSE)
Figure 9: Color tables: native plot with the terra package.
# `autoplot()` method.autoplot(r_coltab, maxcell =Inf, show.legend =FALSE)+labs(title ="autoplot() method")# `geom_spatraster()` method.ggplot()+geom_spatraster(data =r_coltab, maxcell =Inf, show.legend =FALSE)+labs(title ="geom_spatraster() method")# `scale_fill_coltab()` method.ggplot()+geom_spatraster( data =r_coltab, use_coltab =FALSE, maxcell =Inf, show.legend =FALSE)+scale_fill_coltab(data =r_coltab)+labs(title ="scale_fill_coltab() method")# Extract named colors and use `scale_fill_manual()`.cols<-get_coltab_pal(r_coltab)cols|>head()#> Continuous urban fabric #> "#E6004D" #> Discontinuous urban fabric #> "#FF0000" #> Industrial or commercial units #> "#CC4DF2" #> Road and rail networks and associated land #> "#CC0000" #> Port areas #> "#E6CCCC" #> Airports #> "#E6CCE6"# Use the extracted colors.ggplot()+geom_spatraster( data =r_coltab, use_coltab =FALSE, maxcell =Inf, show.legend =FALSE)+scale_fill_manual( values =cols, na.value ="transparent", na.translate =FALSE)+labs(title ="scale_fill_manual() method")
Figure 12: Map with north arrow (top right) and scale bar (bottom left) annotations added using ggspatial.
How to overlay a SpatRaster on an RGB tile
Use geom_spatraster_rgb() for the RGB SpatRaster background tile, then add your data layers on top. Use ggblend to blend the layers, as shown below. For more examples, see My ggplot2 blending adventure by Barney Harris.
While SpatRaster cells are inherently rectangular, you can create plots with hexagonal cells using fortify.SpatRaster() and stat_summary_hex(). The final plot requires coordinate adjustment with coord_sf():
library(terra)library(tidyterra)library(ggplot2)holyrood<-"holyroodpark.tif"r<-rast(holyrood)# With a hexagonal grid.ggplot(r, aes(x, y, z =elevation))+stat_summary_hex( fun =mean, color =NA, linewidth =0,# Bin size determines the number of cells displayed. bins =30)+coord_sf(crs =pull_crs(r))+labs( title ="Hexagonal SpatRaster", subtitle ="Using implicit fortify() and stat_summary_hex()", x =NULL, y =NULL)
Figure 15: Elevation data aggregated and visualized as hexagonal grid cells.
You do not need to call fortify.SpatRaster() directly because ggplot2 invokes it implicitly when you use ggplot(data = a_spatraster).
Thanks to this extension mechanism, you can use additional geoms and stats from ggplot2:
# Point plot.ggplot(r, aes(x, y, z =elevation), maxcell =1000)+geom_point(aes(size =elevation, alpha =elevation), fill ="darkblue", color ="grey50", shape =21)+coord_sf(crs =pull_crs(r))+scale_radius(range =c(1, 5))+scale_alpha(range =c(0.01, 1))+labs( title ="SpatRaster as points", subtitle ="Using implicit fortify()", x =NULL, y =NULL)
Figure 16: Elevation data represented as points with size and transparency scaled by elevation values.
tidyterra and metR
metR provides ggplot2 extensions, primarily for meteorological data visualization. As shown previously (see Labeling contours), you can combine both packages to create rich, complex plots.
Figure 17: Relief rendering combining tidyterra for raster plotting and metR for terrain relief representation.
tidyterra and ggblend
ggblend provides operations for blending, copying, adjusting and compositing layers in ggplot2. As shown in How to overlay a SpatRaster on an RGB tile, you can use ggblend with tidyterra to blend raster layers. The following example combines a multidirectional hillshade as described by (Royé 2022) with a colored elevation raster to highlight terrain relief.
# Load libraries and files.# Hillshade with gray colors.slope<-terrain(r, "slope", unit ="radians")aspect<-terrain(r, "aspect", unit ="radians")# Multidirectional shadows.hill<-shade(slope, aspect, 0, c(270, 15, 60, 330))|>mean()hill_plot<-ggplot()+geom_spatraster(data =hill, show.legend =FALSE, maxcell =Inf)+scale_fill_gradient2( high ="white", mid ="gray80", low ="gray20", na.value ="transparent")# Extract the hillshade colors.hill_cols<-layer_data(hill_plot)|>pull(fill)# Use the extracted colors to blend the hillshade with the elevation raster.ggplot()+list(geom_spatraster(data =r),scale_fill_cross_blended_c(breaks =seq(0, 250, 25)),geom_spatraster(data =hill, fill =hill_cols))|>blend("multiply")+guides(fill =guide_legend(reverse =TRUE), alpha ="none")+labs(x ="", y ="", title ="tidyterra and ggblend: Hillshade")
Figure 18: Elevation and hillshade layers plotted with tidyterra and blended using ggblend.