Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a rainbow color scale based on a vector, in the order of that vector

Tags:

r

colors

graphics

I'm looking for a more elegant way to do this:

#Create Dataset
set.seed(1)
x <- runif(100)
y <- runif(100)
z <- y*x

#Assign colors, based on z vector    
Data <- data.frame(Order=1:length(z),z=z)
Data <- Data[order(Data$z),]
Data$col <- rainbow(length(z))
orderedcolors <- Data[order(Data$Order),'col']

#Plot x vs y, colored by z
plot(x,y,col=orderedcolors)

Basically, I want to assign a color to each point in the z vector, and I want those colors to vary on a rainbow scale from z's lowest values to it's highest values.

like image 419
Zach Avatar asked Sep 14 '11 17:09

Zach


1 Answers

Your solution assigns colour to the rank of your data. If that's what you had in mind, then that's great.

However, if you really had in mind that the value of the data should determine the colour, then here is a solution:

First, your code:

#Create Dataset
set.seed(1)
x <- runif(100)
y <- runif(100)
z <- y*x

par(mfrow=c(1,2))
#Assign colors, based on z vector    
Data <- data.frame(Order=1:length(z),z=z)
Data <- Data[order(Data$z),]
Data$col <- rainbow(length(z))
orderedcolors <- Data[order(Data$Order),'col']
plot(x,y,col=orderedcolors, main="Yours")

Next, my code. I use the function colorRamp that creates function that linearly interpolates between colours given the input to the function. Since the input to colorRamp must be in the range [0; 1], I first define a little helper function range01 that scales data between 0 and 1. Finally, since colorRamp gives output in RGB values, I use apply and rgb to get these values back into colours that plot understands:

range01 <- function(x)(x-min(x))/diff(range(x))
rainbow(7)
cRamp <- function(x){
  cols <- colorRamp(rainbow(7))(range01(x))
  apply(cols, 1, function(xt)rgb(xt[1], xt[2], xt[3], maxColorValue=255))
}  

#Plot x vs y, colored by z
plot(x,y,col=cRamp(z), main="Mine")

The results. Notice the different distribution in colours near the axes.

enter image description here

like image 54
Andrie Avatar answered Sep 21 '22 22:09

Andrie