[R] rainbow function

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Jan 7 12:05:35 CET 2008


Wang, Zhaoming (NIH/NCI) [C] wrote:
> Hello
> I'm using rainbow function to generate 10 colors for the plot and it is
> difficult to tell the neighboring colors from each other. How can I make
> the colors more differently.
>  

  If all you want is for neighbouring colours to be distinguishable you 
could just sample(rainbow(10)) until you get a palette with 
neighbouringly distinguishable colours:

# some neighbours look similar:
plot(1:10, col=rainbow(10))

# so try this:
set.seed(1) # so your random numbers are the same as mine...

p = sample(rainbow(10))
plot(1:10, col=p)

# hmmm green and cyan are still next to each other. Lets try again:

p=sample(rainbow(10))
plot(1:10,col=p)

  - and repeat until you are happy with the sequence. Then use the same 
palette in your legend.

This is fine for simple plots where coloured objects are discrete, such 
as in a bar chart, but perhaps wouldn't work for overlapping coloured 
objects, like several time series together or several scatterplots. 
Perhaps use 5 colours and two point types for points, or two line styles 
for lines, or two fill styles for areas.

rainbow() is great - for drawing rainbows - but the palettes from the 
RColorBrewer package are much better for statistical plots as someone 
else suggested. When I write code for plots I try and use RColorBrewer 
if it's there:

getColours <- function(nv=4){
   if(require(RColorBrewer)){
     cols=brewer.pal(nv,"Pastel1")
   }else{
     warning("This plot would like nicer if you installed RColorBrewer")
     cols=(1:nv)
   }
   return(cols)
}


Barry




More information about the R-help mailing list