Create a vector based rainbow color scale in the order of this vector

I am 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 these colors to change in the rainbow scale from the lowest values ​​to the highest values.

+6
source share
3 answers

You did not say how to handle the links, but would this work:

 plot(x,y,col = rainbow(length(z))[rank(z)]) 

It seems that the same output is being generated for me, basically putting the colors in order z using indexing and rank .

+10
source

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)) #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 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.

enter image description here

+12
source

You can simply create a rainbow of colors and then index it creatively.

 orderedcolors2 <- rainbow(length(z))[order(order(z))] 

which gives the same set of colors as the source code

 > identical(orderedcolors2, orderedcolors) [1] TRUE 
+6
source

Source: https://habr.com/ru/post/897336/


All Articles