encode_colour: Encode colours into RGB hex-strings

View source: R/encode.R

encode_colourR Documentation

Encode colours into RGB hex-strings


This is a version of grDevices::rgb() that works with the standard colour format used in farver (matrix or data.frame with colours in rows). It further support taking input from any colour space.


encode_colour(colour, alpha = NULL, from = "rgb", white = "D65")



A numeric matrix (or an object coercible to one) with colours encoded in the rows and the different colour space values in the columns. For all colourspaces except 'cmyk' this will mean a matrix with three columns - for 'cmyk' it means four columns.


A numeric vector between 0 and 1. Will be recycled to the number of rows in colour. If NULL or a single NA it will be ignored.


The input colour space. Allowed values are: "cmy", "cmyk", "hsl", "hsb", "hsv", "lab" (CIE L*ab), "hunterlab" (Hunter Lab), "oklab", "lch" (CIE Lch(ab) / polarLAB), "luv", "rgb" (sRGB), "xyz", "yxy" (CIE xyY), "hcl" (CIE Lch(uv) / polarLuv), or "oklch" (Polar form of oklab)


The white reference of the input colour space. Will only have an effect for relative colour spaces such as Lab and luv. Any value accepted by as_white_ref() allowed.


A character vector with colours encoded as #RRGGBB(AA)

Handling of non-finite and out of bounds values

NA, NaN, -Inf, and Inf are treated as invalid input and will result in NA values for the colour. If a given colourspace has finite bounds in some of their channels, the input will be capped before conversion, and the output will be capped before returning, so that both input and output colours are valid colours in their respective space. This means that converting back and forth between two colourspaces may result in a change in the colour if the gamut of one of the spaces is less than the other.


The output may differ slightly from that of grDevices::rgb() since rgb() doesn't round numeric values correctly.

See Also

Other encoding and decoding functions: decode_colour(), manip_channel


spectrum <- decode_colour(rainbow(10))


# Attach alpha values
encode_colour(spectrum, alpha = c(0.5, 1))

# Encode from a different colour space
spectrum_hcl <- convert_colour(spectrum, 'rgb', 'hcl')
encode_colour(spectrum_hcl, from = 'hcl')

farver documentation built on July 6, 2022, 5:05 p.m.