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 published release documentation. Open the chat button in the lower-right corner of the documentation website or its development version. 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 3: Alternative (metR): contour labeling combining tidyterra and the metR package with customized styling.
Using a different color scale
Since tidyterra builds on ggplot2, refer to ggplot2 documentation on scales.
The following example illustrates hillshading, a terrain visualization technique based on simulated illumination of a surface (Horn 1981).
library(terra)library(tidyterra)library(ggplot2)holyrood<-"holyroodpark.tif"r<-rast(holyrood)# Hillshade with gray colors.slope<-terrain(r, "slope", unit ="radians")aspect<-terrain(r, "aspect", unit ="radians")# Multidirectional shadows.hill<-shade(slope, aspect, 10, c(270, 15, 60, 330))|>mean()ggplot()+geom_spatraster(data =hill, show.legend =FALSE)+# Use a grayscale palette.scale_fill_gradientn( colours =grey(0:100/100), na.value ="transparent")+labs(title ="A hillshade plot with gray colors")
Figure 4: Hillshade plot using grayscale colors to enhance terrain relief.
Can I change the default palette of my maps?
Set the ggplot2.continuous.fill option to change the session default for continuous fill when the plot uses an implicit scale. For example, autoplot() can add its own scale, and geom_spatraster() can use a raster’s color table.
Figure 5: Changing default ggplot2 color palettes.
My map tiles are blurry
Raster tiles can appear blurry after reprojection or downsampling.
Important
For Web Mercator tiles, keep the provider’s native CRS (EPSG:3857) with maptiles::get_tiles(project = FALSE) and use the same CRS for the plot with ggplot2::coord_sf(crs = 3857). Use maxcell = Inf to skip tidyterra’s sampling step. A change in CRS can still resample the tile.
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.
# Plot with `autoplot()`.autoplot(r_coltab, maxcell =Inf, show.legend =FALSE)+labs(title ="autoplot()")# Plot with `geom_spatraster()`.ggplot()+geom_spatraster(data =r_coltab, maxcell =Inf, show.legend =FALSE)+labs(title ="geom_spatraster()")# Add the color table with `scale_fill_coltab()`.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()")# 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.
Use stat_summary_hex() to aggregate raster cell centers into hexagonal bins. The plot uses the coordinates supplied by fortify.SpatRaster(). Set coord_sf(crs = pull_crs(r)) to use the raster’s CRS.
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,# Set the number of bins used to aggregate cell centers. 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.
Figure 18: Elevation and hillshade layers plotted with tidyterra and blended using ggblend.
References
Fick, Stephen E., and Robert J. Hijmans. 2017. “WorldClim 2: New 1-Km Spatial Resolution Climate Surfaces for Global Land Areas.”International Journal of Climatology 37 (12): 4302–15. https://doi.org/10.1002/joc.5086.