Skip to content

Instantly share code, notes, and snippets.

@jonesor
Last active July 18, 2026 20:18
Show Gist options
  • Select an option

  • Save jonesor/55326409f5087a65f048 to your computer and use it in GitHub Desktop.

Select an option

Save jonesor/55326409f5087a65f048 to your computer and use it in GitHub Desktop.
Manipulate a color palette for "heat map" type colour schemes.
#Assume your data are in a data frame.
df1 <- data.frame(x = 1:100)
#Define the basic palette (this case goes from red - yellow - green, but you could make it any 3 colours.)
colCode <- colorRampPalette(c("red", "yellow", "green"))(n = 999)
#Make a vector (of length 999), but break apart the parts of the sequence that should be red yellow and green.
#This allows you to alter where the yellow "pivot point" is.
numValue = c(seq(1,30,length=333), # for red
seq(30,50,length=333), # for yellow
seq(50,100,length=333)) # for green
#put these in a data frame
my_palette<-data.frame(colCode,numValue)
#A function to pick the closest matching numeric value from the palette.
findcol = function(x){my_palette$colCode[which.min(abs(my_palette$numValue - x))]}
#Apply this function to the data vector.
df1$colVal = as.character(unlist(lapply(df1$x,findcol)))
#Plot it.
plot(df1$x,pch=16,col=df1$colVal,cex=2)
#Now try altering the three seq() lines above to see how it alters the sequence of colours.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment