I have this code, which creates a map with a SpatRaster and a "background map" with the help of the maptiles library:
library(terra)
library(maptiles)
# Example raster: global elevation
r <- terra::rast(system.file("ex/elev.tif", package="terra"))
# Original extent and expanded extent
ext_original <- terra::ext(r)
ext_expanded <- terra::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 <- maptiles::get_tiles(ext_expanded, provider = "OpenStreetMap", crop = TRUE, zoom = 8)
terra::plot(osm_rast, axes = T,
mar = c(3.1, 3.1, 2.1, 7.1))
# Plot raster on top
terra::plot(r, add=TRUE, axes = T, grid = T)
This is the plot that produces this output:
Now I'm just going to change the raster file "ex/elev.tif" for my own here is the download link for the file, in this case it's a raster file of the "Rio Trancura, formerly Rio Llafenco" basin. Here's the code:
library(terra)
library(maptiles)
# Example raster: global elevation
r <- terra::rast("C:/Users/wayym/OneDrive/Escritorio/Hidrologia/4Lucass/4Luis/dem_TrancuraAntesDeLlafenco_TanDEM_X_12_5m_noSinks[SAGA]_merged_ALOS_EPSG_4326-onlyCatchment_byMZB.tif")
# Original extent and expanded extent
ext_original <- terra::ext(r)
ext_expanded <- terra::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 <- maptiles::get_tiles(ext_expanded, provider = "OpenStreetMap", crop = TRUE, zoom = 8)
terra::plot(osm_rast, axes = T,
mar = c(3.1, 3.1, 2.1, 7.1))
# Plot raster on top
terra::plot(r, add=TRUE, axes = T, grid = T)
And this is the plot that I get:
I don't know why the grid and the legend gets unconfigured just by changing the file. All the files have the same coord. ref: WGS 84 (EPSG:4326)
Understanding you want to show TrancuraAntesDeLlafenco within a context area, you are starting with two rasters that have very different resolution. osm_transcura resolution : 0.00467, 0.00467 (x, y)
, and transcura_riv resolution : 0.000125664, 0.000125664 (x, y)
I would resample transcura_riv to the osm_transcura resolution.
transcura_resamp <- resample(transcura_riv, osm_transcura, method = 'bilinear')
plot(osm_transcura, axes = TRUE, mar = c(3.1, 3.1, 2.1, 7.1))
plot(transcura_resamp, add = TRUE, axes = TRUE, grid = TRUE)
Simply increasing increasing the extent, which would be done with terra::extend
doesn't solve the resolution mismatch problem. Once resampled, transcura falls into it's proper relation to it's surrounding context.