52

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

Niek de Klein
  • 7,839
  • 18
  • 67
  • 129

3 Answers3

121

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

joran
  • 157,274
  • 30
  • 404
  • 439
  • I feel this may have been fairly intuitive, but just to clarify, the "10" being used in the palette refers to the number of colors in the range. This could even be separated out and assigned to a variable for a more configurable graph. – Broper Dec 01 '18 at 18:53
  • This is fine for siqeuntially increasing data, but what about a point that is lower than the previous point. This color encoding will not show it. – MadmanLee Dec 03 '19 at 00:17
  • Sorry about that joran – MadmanLee Dec 03 '19 at 04:03
21

Solution using ggplot2:

library(ggplot2)

#Some sample data
x <- sort(runif(100))
dat <- data.frame(x = x,y = x^2 + 1)
# Some external vector for the color scale
col <- sort(rnorm(100))

qplot(x, y, data=dat, colour=col) + scale_colour_gradient(low="red", high="blue")

plot

ROLO
  • 4,093
  • 21
  • 40
17

To add a legend to joran's answer in base R:

legend("topleft",title="Decile",legend=c(1:10),col =rbPal(10),pch=20)

This example adds ",cex=0.8" just for prettiness:

multicoloured plot including legend

purplemac
  • 181
  • 1
  • 3