Merging and plotting raster files in R

When plotting raster elevation files, you might need to merge a few files to cover your area of interest. Here is how I did it in R.

# Load libraries
library(terra)

# Set working directory
setwd("C:\\Eget\\R\\")

# Paths to raster files to read
tif_file1 <- "Indata\\DEM_Gbg\\6398_145.tif"
tif_file2 <- "Indata\\DEM_Gbg\\6398_146.tif"
tif_file3 <- "Indata\\DEM_Gbg\\6399_145.tif"
tif_file4 <- "Indata\\DEM_Gbg\\6399_146.tif"

# Read files as raster objects
raster1 <- rast(tif_file1)
raster2 <- rast(tif_file2)
raster3 <- rast(tif_file3)
raster4 <- rast(tif_file4)

# Merge raster files
combined_raster <- merge(raster1, raster2, raster3, raster4)

# Set colour interval
color_intervals <- seq(0, 100, by = 10)

# Create palette
color_palette <- terrain.colors(length(color_intervals))

# Plot result
plot(combined_raster, col = color_palette, breaks = color_intervals,
     main = "Terrain model")

The data, again, comes from Gothenburg.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait