Skip to content

Instantly share code, notes, and snippets.

@Jfortin1
Last active September 2, 2023 20:42
Show Gist options
  • Save Jfortin1/72ef064469d1703c6b30 to your computer and use it in GitHub Desktop.
Save Jfortin1/72ef064469d1703c6b30 to your computer and use it in GitHub Desktop.
Darken or lighten colors in R
darken <- function(color, factor=1.4){
col <- col2rgb(color)
col <- col/factor
col <- rgb(t(col), maxColorValue=255)
col
}
lighten <- function(color, factor=1.4){
col <- col2rgb(color)
col <- col*factor
col <- rgb(t(col), maxColorValue=255)
col
}
# Example:
darkFirebrick <- darken("firebrick")
@alexpreynolds
Copy link

This seems to work:

lighten <- function(color, factor=1.4){
    col <- col2rgb(color)
    col <- col*factor
    col <- rgb(t(as.matrix(apply(col, 1, function(x) if (x > 255) 255 else x))), maxColorValue=255)
    col
}

@Nate-Wessel
Copy link

Thanks for sharing this! Very useful!

@alexpreynolds
Copy link

alexpreynolds commented Dec 29, 2017

Here's an example of how to use this with a column vector via sapply():

chromatin_state_colors <- c('Red', 'OrangeRed', 'LimeGreen', 'Green', 'DarkGreen', 'GreenYellow', '#E5E500', '#3D7B66', 'PaleTurquoise', 'IndianRed', 'DarkSalmon', 'DarkKhaki', 'gray50', 'Gainsboro', 'whitesmoke')
lightened_chromatin_state_colors <- sapply(chromatin_state_colors, lighten)
darkened_chromatin_state_colors <- sapply(chromatin_state_colors, darken)

@joachim-gassen
Copy link

Thanks!
For lighten() the following appeared more natural to me. Larger factors make color more light with a factor of 1 generating white:

lighten <- function(color, factor = 0.5) {
  if ((factor > 1) | (factor < 0)) stop("factor needs to be within [0,1]")
  col <- col2rgb(color)
  col <- col + (255 - col)*factor
  col <- rgb(t(col), maxColorValue=255)
  col
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment