Last active
March 20, 2023 22:58
-
-
Save ratnanil/a8dbd17d7c3045236178f20285cefdb3 to your computer and use it in GitHub Desktop.
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
# from here: | |
# https://github.com/rstudio/gt/blob/ff878e10d21a3ba897c5f99801b796da8fb637fa/R/helpers.R#L2496-L2536 | |
adjust_luminance <- function(colors, steps) { | |
stopifnot(steps < 2, steps > -2) | |
rgb_matrix <- t(grDevices::col2rgb(colors, alpha = TRUE)) / 255 | |
alpha <- rgb_matrix[, "alpha"] | |
luv_matrix <- | |
grDevices::convertColor(rgb_matrix[, 1:3], "sRGB", "Luv") | |
h <- atan2(luv_matrix[, "v"], luv_matrix[, "u"]) * 180 / pi | |
c <- sqrt(luv_matrix[, "u"]^2 + luv_matrix[, "v"]^2) | |
l <- luv_matrix[, "L"] | |
y <- l / 100. | |
x <- log(-(y / (y - 1))) | |
y_2 <- 1 / (1 + exp(-(x + steps))) | |
l <- y_2 * 100. | |
grDevices::hcl(h, c, l, alpha = alpha) | |
} | |
bivariate_matrix_luminocity <- | |
function(mypal, | |
n = length(mypal), | |
combine_with = "cbind") { | |
library(purrr) | |
accumulate(seq_len(n - 1), \(x, y) adjust_luminance(x, 1), .init = mypal) |> | |
rev() |> | |
(\(x) do.call(combine_with, x))() | |
} | |
bivariate_matrix_alpha <- | |
function(mypal, | |
n = length(mypal), | |
alpha_range = c(0, 1)) { | |
rgb_mat <- col2rgb(mypal) / 255 | |
a_from <- alpha_range[1] | |
a_to <- alpha_range[2] | |
alpha_seq <- seq(a_from, a_to, (a_to - a_from) / (n - 1)) | |
sapply(alpha_seq, function(alpha) { | |
apply(rgb_mat, 2, \(x) rgb(x[1], x[2], x[3], alpha)) | |
}) | |
} | |
mypal <- RColorBrewer::brewer.pal(3,"Spectral") | |
bivariate_matrix_luminocity(mypal) |> | |
scales::show_col() | |
bivariate_matrix_alpha(mypal,alpha_range = c(0.2, 0.8)) |> | |
scales::show_col() | |
Author
ratnanil
commented
Mar 20, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment