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

RColorsPlotGradient

R Problem Overview


I'm plotting the figure 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?

plot

R Solutions


Solution 1 - R

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

Solution 2 - R

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

Solution 3 - R

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

Solution 4 - R

colorRamp() returns a function for assigning colors to numbers within a 0:1 interval.

pal <- colorRamp(c("blue", "green", "orange", "red"))

Now rgb() can be used to get a usable color out of this function:

rgb(pal(0.5), max=255)
[1] "#7FD200"

Hence, if the vector is transformed to a range 0-1 then pal() can be used for color assignment.

Full demonstration:

x <- rnorm(1000)

# NOTE: (x-min(x)) / diff(range(x)) transforms x to have a range of 0:1
pal <- colorRamp(c("blue", "green", "orange", "red"))    # 1) choose colors
col <- rgb(pal((x - min(x)) / diff(range(x))), max=255)  # 2) interpolate numbers

plot(x, col=col, pch=19)

img

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiek de KleinView Question on Stackoverflow
Solution 1 - RjoranView Answer on Stackoverflow
Solution 2 - RROLOView Answer on Stackoverflow
Solution 3 - RpurplemacView Answer on Stackoverflow
Solution 4 - RKarolis KoncevičiusView Answer on Stackoverflow