[英]How to write a facet_wrap (ggplot2) within a function
我写了一个函数来绘制条形图。 但是当我开始刻面时,'〜'标志让事情变得困难。
rf.funct <- function(dat, predictor, feature){
ggplot(get(dat), aes(get(predictor), N)) +
geom_bar(stat = 'identity') +
facet_wrap(get(~feature)) # this is where the problem is
}
我尝试了以下方法:
facet_wrap((get(~feature))) # invalid first argument
facet_wrap(paste0("~ ", get(feature))) # object 'feature' not found
我如何确保函数中包含“~”符号?
你不需要使用get
。 您已经使用dat
参数将数据框传递给函数,因此只需将dat
提供给 ggplot,它就会从其环境中获取数据。
rf.funct <- function(dat, predictor, feature) {
ggplot(dat, aes_string(predictor, "N")) +
geom_bar(stat = 'identity') +
facet_wrap(feature)
}
predictor
和feature
参数应作为字符串输入。 然后你可以使用aes_string
来指定美学。 facet_wrap
现在可以直接获取字符向量,无需公式(正如@WeihuangWong 所指出的)。
我遇到了类似的问题,这里的答案和评论帮助我解决了这个问题。 然而,这篇文章现在已经有 6 年的历史了,我认为最现代的解决方案是这样的:
rf.funct <- function(dat, predictor, feature){
ggplot(dat, aes({{predictor}}, N)) +
geom_bar(stat = 'identity') +
facet_wrap(enquo(feature))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.