View source: R/rgb_brightness.R
rgb_brightness | R Documentation |
Calculate the perceived brightness of an rgb color matrix
rgb_brightness(col_mat, rgb_fx = NULL)
col_mat |
(required) An rgb matrix; most typically, the output from |
rgb_fx |
(optional) A named numeric vector of weights for each of |
Mainly useful to set a threshold for contrasting label purposes. Perceived brightness is of course subjective, and there is no single definitive calculation approach This function is not meant to be compliant with any standards or technical specifications. It simply implements an approach using defaults as shown here.
A numeric vector of equal length to the input, with values ranging from 0
to 255
.
# contrast is subjective, so you will want to tweak the cutoff depending # on audience, palette, presentation format, etc. # this shows dark-light-dark as an example gradient_fun <- colorRampPalette(c("black", "white", "black"), space = "rgb") # set matrix dimensions for plotting n_col = 18 n_row = 20 # make a vector of hex codes from gradient_fun, then calculate # perceived brightness hex_v <- gradient_fun(n_col * n_row) brt_v <- rgb_brightness(col2rgb(hex_v)) # cutoff to switch text color for contrast, using perceived brightness # default black, switch to white text if < cutoff cutoff <- 140 txt_v <- rep("#000000", n_col*n_row) txt_v[brt_v < cutoff] <- "#ffffff" # calculate the position labels pos_y <- rep(seq(0, 1, length.out = n_col), each = n_row) pos_x <- rep(seq(0, 1, length.out = n_row), times = n_col) # plot image(z = matrix(sort(brt_v), ncol = n_col, byrow = FALSE), col = hex_v, main = "Gradient matrix with contrasting label colors based on brightness") text(pos_x, pos_y, labels = as.integer(brt_v), col = txt_v)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.