R/palettes.R

colors_HS <- c(
  `color1` = "#4BD963",
  `color2` = "#6B6666FE",
  `color3` = "#2A7535FE",
  `color4` = "#CCFFD4FE",
  `color5` = "#FFFFFF",
  `color6` = "#48804CFE"
)

#' Function to extract HeavySet colors as hex codes
#'
#' @param ... Character names of the HeavySet colors
#'
HS_cols <- function(...) {
  cols <- c(...)
  if (is.null(cols)) {
    return(colors_HS)
  }
  colors_HS[cols]
}

HS_palettes <- list(
  `main` = HS_cols("color1", "color2", "color3"),
  `bi` = HS_cols("color1", "color2"),
  `all` = HS_cols()
)

#' Return function to interpolate a HS color palette
#'
#' @param palette Character name of palette in HS_palettes
#' @param reverse Boolean indicating whether the palette should be reversed
#' @param ... Additional arguments to pass to colorRampPalette()
#'
#' @importFrom grDevices colorRampPalette
#'
HS_pal <- function(palette = "all",
                   reverse = FALSE,
                   ...) {
  pal <- HS_palettes[[palette]]

  if (reverse) {
    pal <- rev(pal)
  }

  colorRampPalette(pal, ...)
}


# HS_cols()
# HS_cols("color1")
HS_pal(palette = "all")(10)

#' Color scale constructor for HeavySet colors
#'
#' @param palette Character name of palette in HS_palettes
#' @param discrete Boolean indicating whether color aesthetic is discrete or not
#' @param reverse Boolean indicating whether the palette should be reversed
#' @param ... Additional arguments passed to discrete_scale() or scale_color_gradientn(), used respectively when discrete is TRUE or FALSE
#'
#' @importFrom ggplot2 discrete_scale scale_color_gradientn
#'
#' @export
#'
scale_color_HS <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
  pal <- HS_pal(palette = palette, reverse = reverse)

  if (discrete) {
    ggplot2::discrete_scale("colour", paste0("HS_", palette), palette = pal, ...)
  } else {
    ggplot2::scale_color_gradientn(colours = pal(256), ...)
  }
}


#' Fill scale constructor for HeavySet colors
#'
#' @param palette Character name of palette in HS_palettes
#' @param discrete Boolean indicating whether color aesthetic is discrete or not
#' @param reverse Boolean indicating whether the palette should be reversed
#' @param ... Additional arguments passed to discrete_scale() or scale_color_gradientn(), used respectively when discrete is TRUE or FALSE
#'
#' @importFrom ggplot2 discrete_scale scale_fill_gradientn
#'
#' @export
#'
scale_fill_HS <- function(palette = "main", discrete = TRUE, reverse = FALSE, ...) {
  pal <- HS_pal(palette = palette, reverse = reverse)

  if (discrete) {
    ggplot2::discrete_scale("fill", paste0("HS_", palette), palette = pal, ...)
  } else {
    ggplot2::scale_fill_gradientn(colours = pal(256), ...)
  }
}
MarijnJABoer/HeavySetR documentation built on May 22, 2019, 5:31 p.m.