Last active
September 2, 2023 20:42
-
-
Save Jfortin1/72ef064469d1703c6b30 to your computer and use it in GitHub Desktop.
Darken or lighten colors in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
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
Here's an example of how to use this with a column vector via
sapply()
: