从命名列表或向量创建调色板功能?

时间:2016-06-16 15:07:44

标签: r ggplot2

我有一个九种颜色的已知世界,我想用它来创建一个带有函数的用户定义的调色板。

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")

我想做的是按名称创建任意长度的调色板。

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

那么我就像下面这样使用它,

pal1 <- custom_colors(dark_blue, green, gold)

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

我希望pal1pal2成为字符向量(提供给ggplot2)

c("#034772", "#699D46", "#F9C347")
c("#F9C347", "#EA8936", "#C1C2C4", "#58595B")

3 个答案:

答案 0 :(得分:2)

使用match.call捕获参数:

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"

数据

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")

答案 1 :(得分:1)

您可以将列表转换为命名向量,并使用向量名称对其进行子集化。您似乎只需要提取值以便将其传递给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))

答案 2 :(得分:1)

在函数参数中使用...可以定义所需的任意数量的元素。如果它们作为字符串提供,它们可以存储在矢量中。

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

该实现适用于已定义的颜色世界。

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

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