首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何以编程方式更改传递给"fill“的列名?

如何以编程方式更改传递给"fill“的列名?
EN

Stack Overflow用户
提问于 2018-06-27 00:36:06
回答 2查看 103关注 0票数 0

我需要绘制一个区域堆栈图,其中的填充可以通过更改"string holder“变量以编程方式进行更改。下面是我想做的一个例子。

代码语言:javascript
复制
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()

代码语言:javascript
复制
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()

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2018-06-27 01:40:16

这是可行的:

代码语言:javascript
复制
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周围的反引号也是正常工作所必需的。

票数 0
EN

Stack Overflow用户

发布于 2018-12-12 10:53:58

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

代码语言:javascript
复制
library(rlang)

gg <- ggplot( df_plot, aes(x=year, y=`Pctge CC`, fill = !!sym(this_group_label)) )
gg <- gg + geom_area(position = "stack")
gg
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51047696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档