Chose between a pair of contrasting dark and light colors based on a weighted mean of RGB channels of a color. This function implements a simple approach to the choice for a color of a plot element to ensure it is visible against a background color.
Arguments
- colors
A vector of color definitions or color names in the background.
- threshold
numeric A value of luminance in [0..1] indicating the switch point between dark and light background.
- dark.color, light.color
A color definition or color name to return as dark and light colors to contrast light and dark backgrounds respectively.
Details
The switch between dark and light color is based on a quick and dirty approximation of the luminance of colors computed from RGB values. This easily computed approximation seems to work well enough. The default threshold chosen for a switch between black and white may need to be adjusted for other pairs of colors. Graphic devices can differ in the color spaces they support, but this is unlikely to affect the choice between black and white or other pairs of colors with large differences in luminance.
Note
The current implementation of dark_or_light()
ignores
alpha
, the transparency component, of all its arguments.
Examples
dark_or_light("yellow")
#> [1] "black"
dark_or_light("darkblue")
#> [1] "white"
dark_or_light(c("darkblue", "yellow", "red"))
#> [1] "white" "black" "white"
dark_or_light("#FFFFFF")
#> [1] "black"
dark_or_light("#FFFFFF", dark.color = "darkblue", light.color = "lightgrey")
#> [1] "darkblue"
dark_or_light("#000000", dark.color = "darkblue", light.color = "lightgrey")
#> [1] "lightgrey"