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")
@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