Compatibility with other colour packages

# Preview vignette with: devtools::build_rmd("vignettes/compatibility.Rmd")
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(palettes)

Overview

Because palettes supports casting and coercion for colour vectors, it is generally compatible with other colour packages and functions that accept or return colours as a character vector of "#RRGGBB" or "#RRGGBBAA", colour names from grDevices::colors(), or a positive integer that indexes into grDevices::palette().

This vignette shows how to cast and coerce colour vectors with a select number of colour packages. We use the following colour vector for demonstration.

colour_vector <- pal_colour(
  c("#a00e00", "#d04e00", "#f6c200", "#0086a8", "#132b69")
)
colour_vector

The same approaches below will also work for single colour palettes extracted as a colour vector using [[ or $. See the "Subsetting" section in vignette("palettes", package = "palettes") for more details.

colorspace

library(colorspace)

To turn colour vectors into sRGB objects, pass them to colorspace::hex2RGB().

colour_matrix <- hex2RGB(colour_vector)
colour_matrix

To convert colour matrices into a different colour space use as().

as(colour_matrix, "HLS")

To turn colour matrices from any colour space back into colour vectors use colorspace::hex() and as_colour().

colour_strings <- hex(colour_matrix)
colour_strings

as_colour(colour_strings)

farver

library(farver)

To turn colour vectors into the standard form expected by farver, pass them to farver::decode_colour().

colour_matrix <- decode_colour(colour_vector)
colour_matrix

To convert colour matrices into a different colour space use as().

convert_colour(colour_matrix, "rgb", "lab")

To turn colour matrices back into colour vectors use farver::encode_colour() and as_colour().

colour_strings <- encode_colour(colour_matrix)
colour_strings

as_colour(colour_strings)

grDevices

library(grDevices)

To turn colour vectors into the standard form expected by grDevices, pass them to grDevices::col2rgb().

colour_matrix <- col2rgb(colour_vector)
colour_matrix

To convert colour matrices into a different colour space use grDevices::convertColor() with the transpose of the colour matrix.

convertColor(t(colour_matrix), "sRGB", "Lab")

To turn colour matrices back into colour vectors use grDevices::rgb() and as_colour().

colour_strings <- rgb(
  r = colour_matrix[1, ], g = colour_matrix[2, ], b = colour_matrix[3, ],
  maxColorValue = 255
)
colour_strings

as_colour(colour_strings)


Try the palettes package in your browser

Any scripts or data that you put into this service are public.

palettes documentation built on Sept. 11, 2024, 5:57 p.m.