Colour points in a plot differently depending on a vector of values

Niek de Klein picture Niek de Klein · Mar 30, 2012 · Viewed 97.8k times · Source

I'm plotting the plot below using R's plot function. It is a plot of a vector 'shiftTime' of shift in time. I have another vector 'intensity' of the intensity values ranging from ~3 to ~9. I want to color my points in the plot based on those values with a color gradient. The examples I can find color on the value of the actual plotted points, so in this case the values of the vector 'shiftTime'. Is it also possible to use a different vector, as long as the corresponding values are on the same index?

My plot

Answer

joran picture joran · Mar 30, 2012

Here's a solution using base R graphics:

#Some sample data
x <- runif(100)
dat <- data.frame(x = x,y = x^2 + 1)

#Create a function to generate a continuous color palette
rbPal <- colorRampPalette(c('red','blue'))

#This adds a column of color values
# based on the y values
dat$Col <- rbPal(10)[as.numeric(cut(dat$y,breaks = 10))]

plot(dat$x,dat$y,pch = 20,col = dat$Col)

enter image description here