Thursday, November 24, 2011

Define intermediate color steps for colorRampPalette

The following function, color.palette(), is a wrapper for colorRampPalette() and allows some increased flexibility in defining the spacing between main color levels. One defines both the main color levels (as with colorRampPalette) and an optional vector containing the number of color levels that should be put in between at equal distances.

The above figure shows the effect on a color scale (see image.scale) containing 5 main colors (blue, cyan, white, yellow, and red).  The result of colorRampPalette (upper) produces an equal number of levels between the main colors. By increasing the number of intermediate colors between blue-cyan and yellow-red (lower), the number of color levels in the near white range is reduced. The resulting palette, for example, was better in highlighting the positive and negative values of an Emprical Orthogonal Function (EOF) mode.

the function...
```#This is a wrapper function for colorRampPalette. It allows for the
#definition of the number of intermediate colors between the main colors.
#Using this option one can stretch out colors that should predominate
#the palette spectrum. Additional arguments of colorRampPalette can also
#be added regarding the type and bias of the subsequent interpolation.
color.palette <- function(steps, n.steps.between=NULL, ...){

if(is.null(n.steps.between)) n.steps.between <- rep(0, (length(steps)-1))
if(length(n.steps.between) != length(steps)-1) stop("Must have one less n.steps.between value than steps")

fill.steps <- cumsum(rep(1, length(steps))+c(0,n.steps.between))
RGB <- matrix(NA, nrow=3, ncol=fill.steps[length(fill.steps)])
RGB[,fill.steps] <- col2rgb(steps)

for(i in which(n.steps.between>0)){
col.start=RGB[,fill.steps[i]]
col.end=RGB[,fill.steps[i+1]]
for(j in seq(3)){
vals <- seq(col.start[j], col.end[j], length.out=n.steps.between[i]+2)[2:(2+n.steps.between[i]-1)]
RGB[j,(fill.steps[i]+1):(fill.steps[i+1]-1)] <- vals
}
}

new.steps <- rgb(RGB[1,], RGB[2,], RGB[3,], maxColorValue = 255)
pal <- colorRampPalette(new.steps, ...)
return(pal)
}```
Created by Pretty R at inside-R.org

the code to produce the figure...
```#figure
source("image.scale")
png("color.palette.png", height=4, width=4, res=200, units="in")
par(mfcol=c(2,1), omi=c(0.1,0.1,0.1,0.1), mai=c(1,0.2,0.2,0.2))

steps <- c("blue4", "cyan", "white", "yellow", "red4")
pal <- color.palette(steps, space="rgb")
z=1:1000
image.scale(z, col=pal(41), ylab="", xlab="")
box()

steps <- c("blue4", "cyan", "white", "yellow", "red4")
pal <- color.palette(steps, c(20,1,1,20), space="rgb")
z=1:1000
image.scale(z, col=pal(41), ylab="", xlab="")
box()

dev.off()```
Created by Pretty R at inside-R.org