2
votes

I have a for loop that makes interpolation and plots raster graphs by spplot. It gives a single color bar but labels change in every plot. You can see the difference below. enter image description here enter image description here

I want to use the same color bar with same labels in ssplot, but I could not plot the graphs according to the same map legend.

Here is final part of the code

for (...) {

...

WElev.IDW = idw(formula = variable~1, locations = spdf2, newdata = r.pts)

mypath <- file.path("C:","...", paste("WElevMonth", colnames(variable), ".png", sep = ""))

png(filename = mypath)

print(spplot(WElev.IDW["var1.pred"]))

dev.off() }

1

1 Answers

1
votes

stack() your plots, and spplot the RasterStack

s <- stack(raster1, raster2)
spplot(s)

The resulting plot will have one common legend.


If you want all the plots independent of one another, but want to set the limits and breaks of the color scale, use the at argument. Pass at a vector of breaks. See this post.

First, stack all of your rasters so you can quickly calculate the min and max of the stack. The use these values to inform your legend limits and breaks.

# max and min of the stack
max_r  <- cellStats(s, max) # max of raster stack: legend upper limit
min_r  <- cellStats(s, min) # min of raster Stack: legend lower limit
breaks <- (max_r - min_r)/15 # increase denominator for more breaks
lab    <- seq(min_r, max_r, by = breaks) # create the vector of legend breaks

# now run your for loop and within `spplot`, set the same legend with `at`
for(i in 1:n){
  spplot(raster, at = lab)
  ...
}