This document is a compendium of frequently asked questions about using the tidyterra package and their solutions (primarily focused on the integration of terra and ggplot2). You can ask for help or search previous questions using the following links.
This is the default behavior produced by the ggplot2 package. tidyterra color scales (i.e., scale_fill_whitebox_c(), etc.), have by default the argument na.value set to "transparent", that prevents NA values to be filled2.
library(terra)library(tidyterra)library(ggplot2)# Get a raster data from Holyrood Park, Edinburghholyrood<-"holyroodpark.tif"r<-holyrood|>rast()|>filter(elevation>80&elevation<180)# Defaultdef<-ggplot()+geom_spatraster(data =r)def+labs( title ="Default on ggplot2", subtitle ="NA values in grey")# Modify with scalesdef+scale_fill_continuous(na.value ="transparent")+labs( title ="Default colors on ggplot2", subtitle ="But NAs are not plotted")# Use a different scale provided by ggplot2def+scale_fill_viridis_c(na.value ="orange")+labs( title ="Use any fill_* scale of ggplot2", subtitle ="Note that na.value = 'orange'")
Thanks to fortify.SpatRaster() you can use your SpatRaster straight away with the metR package (see Hexagonal grids and other geoms). Use the argument(s) bins/binwidth/breaks to align both labels and lines:
Blurriness is typically related to the tile source rather than the package. Most base tiles are 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. Also, modify the maxcell argument to avoid resampling and ensure the ggplot2 map uses EPSG:3857 with ggplot2::coord_sf(crs = 3857):
This is a long-standing issue in ggplot2 with no satisfactory solution so far. Please see ggplot2/issues/4622 (and consider contributing if you have insights). You can try the following approach:
tidyterra provides several methods for handling SpatRaster objects with color tables. This example uses clc_edinburgh.tif, available online in the data-raw folder, which contains data from the Corine Land Cover Dataset (2018) for Edinburgh3.
library(terra)library(tidyterra)library(ggplot2)# Get a SpatRaster with coltabr_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 packagesplot(r_coltab)
Figure 9: Color tables: Native plot with terra package
# a. autoplotautoplot(r_coltab, maxcell =Inf)+labs(title ="autoplot method")+theme(legend.text =element_text(size =rel(0.7)))# b. geom_spatrasterggplot()+geom_spatraster(data =r_coltab, maxcell =Inf)+labs(title ="geom_spatraster method")+theme(legend.text =element_text(size =rel(0.7)))# c. Using scale_fill_coltabggplot()+geom_spatraster(data =r_coltab, use_coltab =FALSE, maxcell =Inf)+scale_fill_coltab(data =r_coltab)+labs(title ="scale_fill_coltab method")+theme(legend.text =element_text(size =rel(0.7)))# d. Extract named colors and scale_fill_manualcols<-get_coltab_pal(r_coltab)cols#> 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" #> Mineral extraction sites #> "#A600CC" #> Dump sites #> "#A64D00" #> Construction sites #> "#FF4DFF" #> Green urban areas #> "#FFA6FF" #> Sport and leisure facilities #> "#FFE6FF" #> Non-irrigated arable land #> "#FFFFA8" #> Pastures #> "#E6E64D" #> Broad-leaved forest #> "#80FF00" #> Coniferous forest #> "#00A600" #> Mixed forest #> "#4DFF00" #> Natural grasslands #> "#CCF24D" #> Moors and heathland #> "#A6FF80" #> Bare rocks #> "#CCCCCC" #> Intertidal flats #> "#A6A6E6" #> Water bodies #> "#80F2E6" #> Estuaries #> "#A6FFE6" #> Sea and ocean #> "#E6F2FF"# And nowggplot()+geom_spatraster(data =r_coltab, use_coltab =FALSE, maxcell =Inf)+scale_fill_manual( values =cols, na.value ="transparent", na.translate =FALSE)+labs(title ="scale_fill_manual method")+theme(legend.text =element_text(size =rel(0.7)))
(a) autoplot method
(b) geom_spatraster method
(c) scale_fill_coltab method
(d) named colors and scale_fill_manual method
Figure 10: Color tables: tidyterra package
Use with gganimate
Absolutely! Here is an example (thanks to @frzambra):
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 hex gridggplot(r, aes(x, y, z =elevation))+stat_summary_hex( fun =mean, color =NA, linewidth =0,# Bins size determines the number of cells displayed bins =30)+coord_sf(crs =pull_crs(r))+labs( title ="Hexagonal SpatRaster", subtitle ="Using fortify (implicit) and stat_summary_hex", x =NULL, y =NULL)
Figure 15: Elevation data aggregated and visualized as hexagonal grid cells.
Note that you do not need to call fortify.SpatRaster() directly; 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 plotggplot(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 fortify (implicit)", x =NULL, y =NULL)
Figure 16: Elevation data represented as points with size and transparency scaled by elevation values.
tidyterra and metR
metR is a package that provides ggplot2 extensions, primarily for meteorological data visualization. As shown previously (see Labeling contours), you can combine both packages to create rich, complex plots.