[R] plotting points in random but different colors based on condition

Jim Lemon jim at bitwrit.com.au
Sat Oct 10 09:41:30 CEST 2009


On 10/10/2009 11:10 AM, Jonathan Bleyhl wrote:
> On a similar note, I'm trying to plot continuous values on the y vs.
> categorical (dates) on the x and I want to color by date, but I want the
> colors to be random so points close to each other are easily
> distinguishable. Any thoughts?
>
> Thanks,
> Jon
>
>
> per freem-2 wrote:
>    
>> hi all,
>>
>> suppose I have a file with several columns, and I want to plot all points
>> that meet a certain condition (i.e. all points in columns A and B that
>> have
>> a value greater than such and such in column C of the data) in a new but
>> random color.  That is, I want all these points to be colored differently
>> but I dont care what color.  The only concern is that the points will be
>> colored as differently from each other as possible.
>>
>> The specific example I have is a file with three columns, X, Y and ID.  I
>> want to plot all rows from X, Y (i.e. all points) that have the same value
>> (say 1) in their ID column as one color, all points from X, Y that have
>> the
>> same ID column value (say 2) as a different color, etc.  I dont know ahead
>> of time how many values the ID column will have so I can't write a
>> separate
>> plot statement for each of these sets of X, Y rows that have the same ID
>> value.
>>
>> Is there a way to express this in R?
>>      
Hi per freem and Jonathan,
Random colors may not do what you want simply because they're random. 
That is, you can get two adjacent colors that are very similar unless 
you constrain the choice of colors. One way to do this is to bias the 
choice of color constituents "away" from the previous color.

gimmeDiffCol<-function(oldcol) {
  rgbcomp<-col2rgb(oldcol)
  if(rgbcomp[1,1]>127) newred<-sample(rgbcomp[1,1]:255,1)/255
  else newred<-sample(0:rgbcomp[1,1],1)/255
  if(rgbcomp[2,1]>127) newgreen<-sample(rgbcomp[2,1]:255,1)/255
  else newgreen<-sample(0:rgbcomp[2,1],1)/255
   if(rgbcomp[3,1]>127) newblue<-sample(rgbcomp[3,1]:255,1)/255
  else newblue<-sample(0:rgbcomp[3,1],1)/255
  return(rgb(newred,newgreen,newblue))
}

This is only one way to do this, but it might get you out of trouble.

Jim




More information about the R-help mailing list