Skip to contents

This function determines the appropriate contrast colour (either dark or light) for a given set of colours.

Usage

contrast(colour, dark = "black", light = "white")

Arguments

colour

A character vector of colour names or hex codes.

dark

A character string specifying the colour to use for dark contrast (default is "black").

light

A character string specifying the colour to use for light contrast (default is "white").

Value

A character vector of the same length as colour, containing the contrast colours (either dark or light).

Examples

contrast(c("grey20", "grey80"))
#> [1] "white" "black"
contrast(c("#000000", "#FFFFFF"), dark = "navy", light = "yellow")
#> [1] "yellow" "navy"  
library(ggplot2)
dta <- aggregate(
                 x = list(n = rep(1, nrow(mtcars))),
                 by = list(gear = mtcars$gear, cyl = mtcars$cyl),
                 FUN = sum
)

ggplot(dta, aes(x = gear, y = cyl, fill = n,
                colour = after_scale(contrast(fill)))) +
  geom_tile() +
  geom_text(aes(label = n))