#' Chrestos color scale for ggplot
#'
#' Add a Chrestos color palette to the \code{color} or \code{fill} aesthetic of a ggplot.
#'
#' @param palette Name of the color palette (character). Use \code{names(chresos_palettes())} to obtain the
#' names of the implemented color palettes.
#' @param discrete Use a discrete (\code{TRUE}) or continuous (\code{FALSE}) scale.
#' @param reverse Use the selected palette in original (\code{FALSE}) or reversed (\code{TRUE}) order.
#' @param shade Numeric vector in [0,1] that defines the brightness of the palettes. Values higher
#' then 0.5 lead to brighter colors than the original shade, values lower than 0.5 lead to darker colors.
#' @param customPalettes If desired, a named list of custom palettes with the same structure as \code{chresos_palettes()}.
#' @param ... Further arguments to pass to \code{discrete_scale()} or \code{scale_color_gradientn()}.
#'
#' @examples
#'
#' #color on discrete scale
#' iris %>%
#' ggplot(aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
#' geom_point(size = 4, alpha = 0.8) +
#' scale_color_chrestos(palette = "minimal") +
#' theme_light()
#'
#' #color on discrete scale with custom palette (also works with hex codes instead of names)
#' my_palettes<- list(theonlyone = c("dodgerblue", "forestgreen", "firebrick", "gold"))
#' iris %>%
#' ggplot(aes(x = Petal.Length, y = Petal.Width, color = Species)) +
#' geom_point(size = 4, alpha = 0.8) +
#' scale_color_chrestos(palette = "theonlyone", customPalettes = my_palettes) +
#' theme_light()
#'
#' #fill on continuous scale with reverse palette
#' faithfuld %>%
#' ggplot(aes(x = waiting, y = eruptions, fill = density)) +
#' geom_raster(interpolate = TRUE) +
#' scale_fill_chrestos(palette = "grad4", discrete = FALSE, reverse = TRUE) +
#' theme_void()
#'
#' @name scale_chrestos
NULL
#' @rdname scale_chrestos
#'
#' @export
#'
scale_color_chrestos <- function(palette = "main", discrete = TRUE, reverse = FALSE, shade = 0.5, customPalettes = NULL, ...) {
pal <- create_palfun(palette = palette, reverse = reverse, customPalettes = customPalettes, shade = shade)
if (discrete) {
fun <- ggplot2::discrete_scale(aesthetics = "colour", scale_name = paste0("chrestos_", palette), palette = pal, ...)
} else {
fun <- ggplot2::scale_color_gradientn(colours = pal(256), ...)
}
return(fun)
}
#' @rdname scale_chrestos
#'
#' @export
#'
scale_fill_chrestos <- function(palette = "main", discrete = TRUE, reverse = FALSE, shade = 0.5, customPalettes = NULL, ...) {
pal <- create_palfun(palette = palette, reverse = reverse, shade = shade)
if (discrete) {
fun <- ggplot2::discrete_scale(aesthetics = "fill", scale_name = paste0("chrestos_", palette), palette = pal, ...)
} else {
fun <- ggplot2::scale_fill_gradientn(colours = pal(256), ...)
}
return(fun)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.