我需要绘制一个区域堆栈图,其中的填充可以通过更改"string holder“变量以编程方式进行更改。下面是我想做的一个例子。
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
发布于 2018-06-27 01:40:16
这是可行的:
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周围的反引号也是正常工作所必需的。
发布于 2018-12-12 10:53:58
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")
gghttps://stackoverflow.com/questions/51047696
复制相似问题