如何以编程方式更改传递给“填充”的列名?

时间:2018-06-26 16:36:06

标签: r ggplot2

我需要绘制一个区域堆栈图,在其中可以通过更改“字符串持有人”变量以编程方式更改填充。这是我想做的一个例子。

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes(x = year, y = `Pctge CC`, fill = this_group_label))
gg <- gg + geom_area(position = "stack")
gg

以便在处理具有不同列名的新数据框时可以更改存储在this_group_label中的字符串。

我尝试过aes_string()

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = this_group_label))
gg <- gg + geom_area(position = "stack")
gg

get()

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes(x = year, y = `Pctge CC`, fill = get(this_group_label)))
gg <- gg + geom_area(position = "stack")
gg

无济于事。当我尝试这最后两个时,出现错误Error in FUN(X[[i]], ...) : object 'Roots' not found

2 个答案:

答案 0 :(得分:0)

这有效:

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
fill_label <- paste0("`", this_group_label, "`")
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = fill_label))
gg <- gg + geom_area(position = "stack")
gg

请注意,Pctge CC周围的反引号对于此功能也是必需的。

答案 1 :(得分:0)

rlang::sym接受一个字符串并将其转换为符号。您只需要使用!! unquote即可,因为aes需要未计算的表达式:

library(rlang)

gg <- ggplot( df_plot, aes(x=year, y=`Pctge CC`, fill = !!sym(this_group_label)) )
gg <- gg + geom_area(position = "stack")
gg