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