R/scales.R

Defines functions scale_fill_okcolors scale_color_okcolors

Documented in scale_color_okcolors scale_fill_okcolors

#' Custom ggplot2 Color Scale using okcolors Palettes
#'
#' Applies a custom discrete or continuous color scale to ggplot2 plots using a selected palette from the okcolors package.
#'
#' @param palette Character. Name of the palette to use. Must be one of the palettes available in `okcolors()`. Default is `"obsession"`.
#' @param discrete Logical. Whether to use a discrete scale (`TRUE`) or a continuous scale (`FALSE`). Default is `TRUE`.
#' @param ... Additional arguments passed to `ggplot2::discrete_scale()` or `ggplot2::scale_color_gradientn()`.
#'
#' @return A `Scale` object that can be added to a ggplot2 plot.
#' @examples
#' library(ggplot2)
#' ggplot2::ggplot(ggplot2::mpg, ggplot2::aes(displ, hwy, color = class)) +
#'   ggplot2::geom_point(size = 3) +
#'   scale_color_okcolors("obsession")
#'
#' ggplot2::ggplot(ggplot2::mpg, ggplot2::aes(displ, hwy, color = hwy)) +
#'   ggplot2::geom_point(size = 3) +
#'   scale_color_okcolors("skyscrapers", discrete = FALSE)
#'
#' @export
scale_color_okcolors <- function(palette = "obsession", discrete = TRUE, ...) {
  if (discrete) {
    ggplot2::discrete_scale(aesthetics = "colour", palette = function(n) okcolors(palette, n), ...)
  } else {
    pal_fn <- grDevices::colorRampPalette(okcolors(palette))  # create a function
    ggplot2::scale_color_gradientn(colours = pal_fn(256), ...)
  }
}

#' Custom ggplot2 Fill Scale using okcolors Palettes
#'
#' Applies a custom discrete or continuous fill scale to ggplot2 plots using a selected palette from the okcolors package.
#'
#' @param palette Character. Name of the palette to use. Must be one of the palettes available in `okcolors()`. Default is `"obsession"`.
#' @param discrete Logical. Whether to use a discrete scale (`TRUE`) or a continuous scale (`FALSE`). Default is `TRUE`.
#' @param ... Additional arguments passed to `ggplot2::discrete_scale()` or `ggplot2::scale_fill_gradientn()`.
#'
#' @return A `Scale` object that can be added to a ggplot2 plot.
#' @examples
#' ggplot2::ggplot(ggplot2::mpg, ggplot2::aes(class, fill = class)) +
#'   ggplot2::geom_bar() +
#'   scale_fill_okcolors("skyscrapers")
#'
#' ggplot2::ggplot(ggplot2::mpg, ggplot2::aes(displ, hwy, fill = hwy)) +
#'   ggplot2::geom_tile() +
#'   scale_fill_okcolors("obsession", discrete = FALSE)
#'
#' @export
scale_fill_okcolors <- function(palette = "obsession", discrete = TRUE, ...) {
  if (discrete) {
    ggplot2::discrete_scale(aesthetics = "fill", palette = function(n) okcolors(palette, n), ...)
  } else {
    pal_fn <- grDevices::colorRampPalette(okcolors(palette))
    ggplot2::scale_fill_gradientn(colours = pal_fn(256), ...)
  }
}

Try the okcolors package in your browser

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

okcolors documentation built on June 8, 2025, 9:42 p.m.