Search code examples
rrasterterra

plot shapefile over multipanel raster using terra


I have four rasters and a shapefile. I want to plot shapefile on top of 4 rasters in a single panel

  library(terra)
  r1 <- r2 <- r3 <- r4 <- rast(ncol=10, nrow=10, xmin=-150, xmax=-80, ymin=20, ymax=60)
  
  values(r1) <- runif(ncell(r1))
  values(r2) <- runif(ncell(r2))
  values(r3) <- runif(ncell(r3))
  values(r4) <- runif(ncell(r4))

  rr <- c(r1, r2, r3, r4)
  
  # shapefile 
  lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
  lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
  lonlat <- cbind(lon, lat)
  pols <- vect(lonlat, type="polygons", crs="epsg:4326")
  
  terra::plot(rr)      
  terra::plot(pols, add = T)      

However, the shapefile is not being added to the raster rather it is being plotted in the middle.

enter image description here


Solution

  • Your example data

    library(terra)
    r <- rast(ncol=10, nrow=10, nlyr=4, xmin=-150, xmax=-80, ymin=20, ymax=60) 
    values(r) <- 1:size(r)
    # polygons
    lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
    lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
    pols <- vect(cbind(lon, lat), type="polygons", crs="+proj=longlat +datum=WGS84")
      
    

    Solution

    plot(r, fun=function()lines(pols))