Creating a Shared Legend for Multiple Raster Plots using 'levelplot' in R

66 Views Asked by At

I'm currently working on plotting three raster images using the levelplot function in R. I'd like to have a shared legend for these plots. While using stack to combine the rasters does give me the desired result , I'm curious if there's a more efficient or alternative approach to achieve this without messing up the axis labels and ticks. I also have to add separate text to each subplot which I cannot achieve with stack.

I tried 3 approaches. Below is my current code:

raster_layer1<-raster(matrix(runif(100 *100, min = 50, max = 800), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)
raster_layer2<-raster(matrix(runif(100 *100, min = 50, max = 500), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)
raster_layer3<-raster(matrix(runif(100 *100, min = 50, max = 300), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)

Not the desired output:

s<-stack(raster_layer1,raster_layer2,raster_layer3)

color_range <- colorRampPalette(c("aliceblue","cadetblue1", "deepskyblue3","darkblue"))
my_colors <- color_range(9)
my.at=c(seq(0,240,by=30),Inf)
my.brks=c(seq(0,240,by=30),Inf,cex=2)
myColorkey<- list(at=my.at, labels=c("0","100","200","300","400","500","600","700","800","Inf"))


levelplot(s, col.regions=my_colors, at=my.at, colorkey=myColorkey,
          margin=F,
          cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
          xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

Here I have an output I prefer but it has legend for each plot.

    one<-levelplot(raster_layer1, col.regions=my_colors, at=my.at, colorkey=myColorkey,
          margin=F,
          cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
          xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

two<-levelplot(raster_layer2, col.regions=my_colors, at=my.at, colorkey=myColorkey,
               margin=F,
               cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
               xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))


three<-levelplot(raster_layer3, col.regions=my_colors, at=my.at, colorkey=myColorkey,
               margin=F,
               cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
               xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))


post<-grid.arrange(one,two,three,ncol=3)

Draw colorkey gives a different color and im unsure how to fix that:

k<-draw.colorkey(myColorkey)
post<-grid.arrange(one,two,three,k,ncol=4)
0

There are 0 best solutions below