Your decision assigns a color rank to your data. If this is what you had in mind, then this is great.
However, if you really meant that value data should determine the color, then here is the solution:
First, your code:
#Create Dataset set.seed(1) x <- runif(100) y <- runif(100) z <- y*x par(mfrow=c(1,2))
Next up is my code. I use the colorRamp function, which creates a function that linearly interpolates between colors, given the input of the function. Since the input to colorRamp must be in the range [0; 1], I first define a small helper function range01 that scales the data between 0 and 1. Finally, since colorRamp gives the result in RGB values, I use apply and rgb to return these values ββto the colors that the 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")
Results. Note the different color distribution next to the axes.

source share