Search code examples
rggplot2raster

select highest value in Raster stack and show layer name as legend


I have got a raster stack of 4 raster and created a single raster with each cell showing the highest value across the 4 layers as follows:

library(raster)
stack_raster <- list()
var_name <- c("tmax","tmin","drought","flood")
for(i in seq_along(var_name)){
    var_ref <- var_name[i]
    r <- raster(ncol=10, nrow=10)
    names(r) <- var_ref
    set.seed(i)
    values(r) <- sample(100)
    stack_raster[[i]] <- r
  }

s <- raster::stack(stack_raster)
max_raster <- whiches.max(s)
plot(max_raster)

enter image description here

However, in the legend, instead of showing the values, I want to show the the name of actual raster that contributed to that value. How can I create such map?


Solution

  • You need which.max(s) instead of whiches.max(s). Then, to plot, the easiest thing is probably to melt the raster into a data frame and assign the labels to the value column and use ggplot to draw the result with geom_tile or geom_raster

    max_raster <- which.max(s)
    df <- reshape2::melt(as.matrix(max_raster))
    df$value <- factor(var_name[df$value], var_name)
    
    library(ggplot2)
    
    ggplot(df, aes(Var2, Var1, fill = value)) +
      geom_tile() +
      scale_y_reverse() +
      coord_equal() +
      scale_fill_brewer(palette = 'Set1') +
      theme_light()
    

    enter image description here