Search code examples
rraster

Adding raster values when plotting a whole raster stack


How can I add raster values while plotting the whole raster stack using text()? it can be managed easily while plotting a single raster but I am puzzled how I can do it for a whole raster stack.

example data:

set.seed(123)
library(raster)
r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3)
rr <- lapply(1:10, function(i) setValues(r1,seq(1,ncell(r1),1)))
s <- stack(rr)

for a single raster it is as below:

plot(s[[1]])
text(s[[1]])

Solution

  • You can adjust the graphical parameter par and loop through the layers for plotting instead of using plot on the entire stack:

    set.seed(123)
    library(raster)
    r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3)
    rr <- lapply(1:10, function(i) setValues(r1,seq(1,ncell(r1),1)))
    s <- stack(rr)
    
    # 3 rows, 4 columns
    par(mfrow=c(3,4))
    
    for (ii in 1:nlayers(s)){
    
      plot(s[[ii]])
      text(s[[ii]])
    
    }
    

    enter image description here