I am a bit new to R. Problem summary: I have several raster stacks that share the same spatial extent and time stamp/step. Each stack holds a time series for a unique variable. I want to use rasterVis::levelplot to visualize the rasters such that each variable in the stack occupies a column in a levelplot lattice/trellis(?) and displays the sequential years (at a decadal scale) along the rows with the earliest at the top and most recent at the bottom. each column of plots needs to share a color scale legend, but each column requires its own, as the ranges are quite different.

I have attempted to mock this issue up using the elev.tif raster that comes with terrs. See code below:


# import rasters to stack
f <- system.file("ex/elev.tif", package="terra")
r<-c( rast(f) , rast(f) , rast(f) , rast(f)*10 , rast(f)*10 , rast(f)*10)

# rename by variable and year
names(r)<-c("var1:1990" , "var1:2000" , "var1:2010" , "var2:1990" , "var2:2000", "var2:2010")

#plot with levelplot
levelplot( r,layout=c(2,3))

The result is this:

Current Result

What I would like is this, which ws made from 2 separate plots in Gimp: (note the scales are different by 3 orders of magnitude) Desired Result made with Gimp from 2 plots

I have looked here https://oscarperpinan.github.io/rastervis/FAQ.html#several_rasters and seen a 'split' call to parse out panels generated by a single raster stack. However, each panel was treated individually, and there was no clear way outlined to group the columns together.

I have also tried to combine sequential levelplots; ie:

f <- system.file("ex/elev.tif", package="terra")
r1 <-c( rast(f) , rast(f) , rast(f) )
r2 <- c( rast(f)*10 , rast(f)*10 , rast(f)*10 )

lvp1 <- levelplot(r1)
lvp2 <- levelplot(r2)
lvp <- c(lvp1, lvp2)

This appears promising; however, this will reside inside a loop that will fetch rasters from different directories. I would need to:

  1. create an empty levelplot to append to
  2. keep the different plots for each column on their own scale/legend.

After some further delving into forums, I found a fairly eloquent solution. In my application, the loop iterates over directories where raster files reside that are made into raster stacks with terra. In my application, the rasters in each directory have significantly different ranges in z, so unique scales for each stack/column is critical.

For this example, I generated a reproducible example to illustrate how I worked out the solution using the built in raster 'elev.tif' that is made into a stack twice:

f <- system.file("ex/elev.tif", package="terra")

for (r in 1:2)  {
  r1 <-c( rast(f) , rast(f) , rast(f) )
  LVP[[i]]<- levelplot ( r1,

Here is the outcome: enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.