Uses the algorithm mentioned at https://stackoverflow.com/a/3943023/2022615 based on the luminance of the background color to determine black or white text. The threshold favored black text in a way that didn't look good with our plots, so I increased the threshold from 0.179 to 0.333.pull/18/merge
| Suggests: | Suggests: | ||||
| knitr, | knitr, | ||||
| roxygen2, | roxygen2, | ||||
| viridis | |||||
| viridis, | |||||
| testthat | |||||
| VignetteBuilder: | VignetteBuilder: | ||||
| knitr | knitr | ||||
| Encoding: UTF-8 | Encoding: UTF-8 |
| set_text_color <- function(a) ifelse(apply(col2rgb(a), 2, mean) > 127, "black", "white") | |||||
| #' Animates a plot | #' Animates a plot | ||||
| #' | #' | ||||
| #' @param d a preprocessed dataset | #' @param d a preprocessed dataset |
| set_text_color <- function(x, black = "#000000", white = "#FFFFFF") { | |||||
| # x = color_hex | |||||
| color_rgb <- col2rgb(x) | |||||
| # modified from https://stackoverflow.com/a/3943023/2022615 | |||||
| # following W3 guidelines: https://www.w3.org/TR/WCAG20/#relativeluminancedef | |||||
| color_rgb <- color_rgb / 255 | |||||
| color_rgb[color_rgb <= 0.03928] <- color_rgb[color_rgb <= 0.03928]/12.92 | |||||
| color_rgb[color_rgb > 0.03928] <- ((color_rgb[color_rgb > 0.03928] + 0.055)/1.055)^2.4 | |||||
| lum <- t(color_rgb) %*% c(0.2126, 0.7152, 0.0722) | |||||
| lum <- lum[,1] | |||||
| # threshold is supposed to be 0.179 but 1/3 seems to work better for our plots | |||||
| ifelse(lum > 1/3, black, white) | |||||
| } |
| library(testthat) | |||||
| library(tidyverbs) | |||||
| test_check("tidyverbs") |
| context("test-set_text_color") | |||||
| test_that("correct color selection", { | |||||
| colors <- c("#FFFFFF", "#9E788C", "#B679E5", "#4BB757", | |||||
| "#000000", "#0027D8", "#E6071B", "#495B3F") | |||||
| expect_equal(set_text_color(colors), c(rep("#000000", 4), rep("#FFFFFF", 4))) | |||||
| }) |