rastervis icon indicating copy to clipboard operation
rastervis copied to clipboard

Use colortable from the slot "legend" in levelplot

Open oscarperpinan opened this issue 9 years ago • 2 comments

Already implemented in plot3d.

A simple solution was proposed here

library(rasterVis) 
f <- system.file("external/test.grd", package="raster") 
r <- round(raster(f)) 

## assign a color table 
## if the original raster (on disk) had a color table it should already be in this slot 
r@legend@colortable=rainbow(cellStats(r,max)) 
str(r) 

## use the color table instead. Could write a simple wrapper function for this... 
## this might not work for all color tables.... 
cols=r@legend@colortable 
levelplot(r,col.regions=cols,at=0:length(cols)) 

oscarperpinan avatar Sep 06 '15 14:09 oscarperpinan

Any updates on this enhancement?

It seems there is an additional issue if the argument to col.regions is factor, in which case values get re-ordered according to levels, and hence colours are confused? See code below.

Also, the NA value is the colourtable could be tricky: it seems to be the first colour in the colourtable, but might not be reported by user in the attribute table?

 library(rasterVis) 
 library(raster) 

 r <- raster(nrows=5, ncols=5) 
 r[] <- rep(c(1:5), each=5)
 cols <- c("blue", "red", "yellow", "black", "green")

 r@legend@colortable <- c("white", cols)
 plot(r)


 df <- data.frame(ID=1:5, class=as.character(letters[1:5]), cols=cols)
is.factor(df$cols)
 ratify(r)
 levels(r) <- df

 plot(r)
levelplot(r, col.regions=df$cols, at=0:5)
levelplot(r, col.regions=as.character(df$cols), at=0:5)

MatthieuStigler avatar Sep 26 '17 21:09 MatthieuStigler

Any updates on this enhancement?

No, sorry. Nowadays I have less time than desired for improvements.

It seems there is an additional issue if the argument to col.regions is factor, in which case values get re-ordered according to levels, and hence colours are confused?

This is a common problem with factors: I wouldn't use them for a palette. You can set stringsAsFactors = FALSE in the data.frame call.

oscarperpinan avatar Oct 08 '17 14:10 oscarperpinan