Arferion Arferion -4 years ago 100
R Question

Plotting the maximum of a raster stack in R with specific colours

I have a raster stack of 5 rasters (invented examples here in s), and I would like to make two plots of the max and min value from this stack- this is fairly simple using max/ min (a).

r <- raster(nrows=10,ncols=100)
r[] <- rnorm(1000)
s <- stack(r,r,r,r,r)
a<-max(s, na.rm=T)

However, what I want to do is plot but apply raster specific colours. So for example if the max value in a cell was from raster 3 in the stack, that cell in the plot would be coloured red, in the next cell the max value is from raster 5 then that would be green etc... Is there anyway of applying raster specific colours to such a raster stack plot?

I'm sure this is fairly simply, but I'm going around in circles. If anyone has got any ideas I would be very grateful.

Answer Source

You should use which.max instead of max to get which layer is max for each pixel (note that I had to change your exmple data because you were generating a stack with identical rasters):

r1 <- raster(nrows=10,ncols=100, vals =rnorm(1000))
r2 <- raster(nrows=10,ncols=100, vals =rnorm(1000))
r3 <- raster(nrows=10,ncols=100, vals =rnorm(1000))
r4 <- raster(nrows=10,ncols=100, vals =rnorm(1000))
r5 <- raster(nrows=10,ncols=100, vals =rnorm(1000))
s <- stack(r1,r2,r3,r4,r5) 

to have the colors that you want, you just have to assign a proper color table when you plot wheremax

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download