[R] repeating colors in graph
Barry Rowlingson
B.Rowlingson at lancaster.ac.uk
Thu Oct 23 17:17:03 CEST 2003
Thomas Lumley wrote:
> See the help pages for color() and palette(), and perhaps the RColorBrewer
> package.
Splus lets you define colour palettes in its Gui, using a nice little
notation where you specify something like "black 8 white 6 red" to get a
17-colour palette with 8 colours between balck and white and then 6
colours up to red (linearly interpolating RGB values). Here's a little R
function to do something similar:
smoothColours <-
function(...){
###
### usage: smoothColours(colour,[n|colour],...)
### like smoothColours("white",10,"black") 12 colours, white to black
###
args <- list(...)
r <- g <- b <- NULL
while(length(args)>0){
if(!is.character(args[[1]])){
stop("bad args")
}
if(length(args)>1){
if(is.numeric(args[[2]])){
## do interpolate:
from <- col2rgb(args[[1]])
too <- col2rgb(args[[3]])
## generate args[[2]] colours between specified colours:
n <- args[[2]]+2 # add 2 for start and finish
## chop off last one since it will be added on the next iteration:
r <- c(r,seq(from[1,],too[1,],length=n))
i <- length(r)
r <- r[-i]
g <- c(g,seq(from[2,],too[2,],length=n))
g <- g[-i]
b <- c(b,seq(from[3,],too[3,],length=n))
b <- b[-i]
## cut colour and n from list and back we go
args <- args[-(1:2)]
}else{
## insert colour, chop off 1
cc <- col2rgb(args[[1]])
r <- c(r,cc[1,])
g <- c(g,cc[2,])
b <- c(b,cc[3,])
args <- args[-1]
}
}else{
## insert colour, chop off 1
cc <- col2rgb(args[[1]])
r <- c(r,cc[1,])
g <- c(g,cc[2,])
b <- c(b,cc[3,])
args <- args[-1]
}
}
rgb(r,g,b,max=255)
}
You can then do something like:
image(matrix(runif(100),10,10),col=smoothColours("red",5,"green",6,"blue"))
You can use as many "colour",n,"colour" things as you like, as long as
it starts and ends with a colour name. You can even do:
smoothColours("red","green",10,"white")
And you can use "#abcdef" notation too.
Of course, linearly interpolating in RGB might not be the right thing
to do...
Baz
More information about the R-help
mailing list