R/utils.R

Defines functions viz_palette

Documented in viz_palette

#' Show a single palette
#'
#' Display a single palette to see whether it meets your needs.
#' If no \code{num} parameter is given,
#' all the colours in the palette will be displayed.
#' If \code{num} is less than the number of colours in the palette,
#' then only the first \code{num} colours will be displayed.
#' If \code{num} is greater than the number of colours in the palette,
#' then that many colours will be generated by linear interpolation
#' over the vector of colours in the chosen palette.
#' @param pal character, vector of (hexadecimal) colours representing a palette
#' @param ttl character, title to be displayed (the name of the palette)
#' @param num numeric, the number of colours to display
#' @examples
#' viz_palette(vangogh_palettes$StarryNight)
#' viz_palette(vangogh_palettes$StarryNight, "StarryNight")
#' viz_palette(vangogh_palettes$StarryNight, "StarryNight first 4", num = 4)
#' viz_palette(vangogh_palettes$StarryNight, "StarryNight interpolated to 25", num = 25)
#' @return A vector of colors from a single palette
#' @export
#' @importFrom graphics image
#' @importFrom grDevices colorRampPalette
#'
viz_palette <- function(pal, ttl = deparse(substitute(pal)), num = length(pal)) {
  if (num <= 0) {
    stop("'num' should be > 0")
  }
  pal_func <- colorRampPalette(pal)
  image(seq_len(num), 1, as.matrix(seq_len(num)),
    col = pal_func(num),
    main = paste0(ttl, " (", length(pal), " colours in palette, ", num, " displayed)"),
    xlab = "", ylab = "", xaxt = "n", yaxt = "n", bty = "n"
  )
}

Try the vangogh package in your browser

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

vangogh documentation built on May 27, 2022, 9:12 a.m.