Create a color palette function from a named list or vector?

I have a famous nine-color universe that I would like to use to create custom color palettes with a function.

col_universe <- list(dark_blue = "#034772", med_blue = "#2888BC", 
light_blue = "#73B7CE", green = "#699D46", orange = "#EA8936", gold = "#F9C347", 
dark_grey = "#58595B", medium_grey = "#7D7E81",light_grey = "#C1C2C4")

What I like to do is create custom color palettes by name.

custom_colors <- function(color1, color2, color3, ..., color9)

So, I would use it as shown below,

pal1 <- custom_colors(dark_blue, green, gold)

pal2 <- custom_colors(gold, orange, light_grey, dark_grey)

I want pal1u to pal2be character vectors (for passing to ggplot2)

c("#034772", "#699D46", "#F9C347")
c("#F9C347", "#EA8936", "#C1C2C4", "#58595B")
+4
source share
3 answers

Use match.callto capture parameters:

custom_colors <- function(...) {
    cl = match.call(expand.dots = TRUE)
    sapply(cl[-1], function(col) col_universe[[as.character(col)]])
}

custom_colors(dark_blue, green, gold)
[1] "#034772" "#699D46" "#F9C347"

custom_colors(gold, orange, light_grey, dark_grey)
[1] "#F9C347" "#EA8936" "#C1C2C4" "#58595B"

Data

col_universe <- list(dark_blue = "#034772", med_blue = "#2888BC", 
light_blue = "#73B7CE", green = "#699D46", orange = "#EA8936", gold = "#F9C347", 
dark_grey = "#58595B", medium_grey = "#7D7E81",light_grey = "#C1C2C4")
+2
source

. , , ggplot.

col_universe <- list(dark_blue = "#034772", med_blue = "#2888BC", 
light_blue = "#73B7CE", green = "#699D46", orange = "#EA8936", gold = "#F9C347", 
dark_grey = "#58595B", medium_grey = "#7D7E81",light_grey = "#C1C2C4")

pal1 <- c('dark_blue', 'green', 'gold')

ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species)) + geom_point() + 
  scale_color_manual(values = unname(col_universe[pal1]))

,

custom_palette = function(universe, palette) {
  return(unname(universe[palette]))
}

ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species)) + geom_point() + 
  scale_color_manual(values = custom_palette(col_universe, pal1))
+1

Using ...function arguments allows you to define any number of elements that you need. They can be saved in a vector if they are represented as character strings.

custom_colors <- function(universe, ...){
    col.names <- c(...)
    cols <- sapply(col.names, FUN=function(x) universe[[x]])
    return(unname(cols))
}

The implementation works for a specific color universe.

custom_colors(col_universe, "green", "med_blue")
[1] "#699D46" "#2888BC"

custom_colors(col_universe, "dark_blue", "gold", "orange")
[1] "#034772" "#F9C347" "#EA8936"
+1
source

All Articles