rr-rasterterra

How can I add a "background map" without altering the format of a map made with the Terra library?


I have a raster map code with the Terra library that adds some extensions and I want to add an openstreetmap type background map to it:

library(terra)

# Example raster
r <- rast(system.file("ex/elev.tif", package="terra"))

# Original extent
ext_original <- ext(r)

# Expanded extent (larger on all sides)
ext_expanded <- ext(
xmin(ext_original) - 1,
xmax(ext_original) + 1,
ymin(ext_original) - 1,
ymax(ext_original) + 1
)

# Expanded raster (with NA in the new areas)
r_expanded <- extend(r, ext_expanded)

# Plot 1: original raster
plot(r, main = "Original raster with normal extent")

# Plot 2: expanded raster (larger, with NA on the edges)
plot(r_expanded, main = "Raster with expanded extent")

This is the raster plot without the background map.

enter image description here

Now add the "background map" to the previous code with the maptiles library:

library(terra)
library(maptiles)

# Example raster: global elevation
r <- rast(system.file("ex/elev.tif", package="terra"))

# Original extent and expanded extent
ext_original <- ext(r)
ext_expanded <- ext(
xmin(ext_original) - 1,
xmax(ext_original) + 1,
ymin(ext_original) - 1,
ymax(ext_original) + 1
)

# Download OSM tile with the expanded extent
osm_rast <- get_tiles(ext_expanded, provider = "OpenStreetMap", crop = TRUE, zoom = 8)

# Plot base map
plot(osm_rast, axes=FALSE, legend=FALSE)

# Plot raster on top
plot(r, add=TRUE)

and this is the map with the "openstreetmap style background map"

enter image description here

My question is, how can I make the "background map" respect the format and be added correctly to the plot without the background? I simply want the map from the first image, but with the "background map," but when I do this, the entire map gets bigger and seems to not respect the limits of the ext_expanded variable.


Solution

  • Not sure if I understand the requirements, but try to add margin to your plot, like:

    # Plot base map
    terra::plot(osm_rast, axes = FALSE, 
                mar = c(3.1, 3.1, 2.1, 7.1))
    
    # Plot raster on top
    plot(r, add=TRUE)
    

    enter image description here

    The values c(3.1, 3.1, 2.1, 7.1) are terra's default and were applied in background for your plot(r_expanded, main = "Raster with expanded extent") function.