rgb_brightness: Calculate the perceived brightness of an rgb color matrix

View source: R/rgb_brightness.R

rgb_brightnessR Documentation

Calculate the perceived brightness of an rgb color matrix

Description

Calculate the perceived brightness of an rgb color matrix

Usage

rgb_brightness(col_mat, rgb_fx = NULL)

Arguments

col_mat

(required) An rgb matrix; most typically, the output from grDevices::col2rgb

rgb_fx

(optional) A named numeric vector of weights for each of r,g,b. If provided, must have names of red, green, blue.

Details

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.

Value

A numeric vector of equal length to the input, with values ranging from 0 to 255.

Examples

# 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)

slin30/wzMisc documentation built on Jan. 27, 2023, 1 a.m.