【发布时间】:2017-09-10 09:03:27
【问题描述】:
library(dplyr) #Devel version, soon-to-be-released 0.6.0
library(tidyr)
library(ggplot2)
library(forcats) #for gss_cat data
我正在尝试编写一个函数,将即将发布的dplyr devel 版本中的quosures 与tidyr::gather 和ggplot2 结合起来。到目前为止,它似乎与tidyr 一起工作,但我在绘图时遇到了麻烦。
以下函数似乎适用于tidyr's gather:
GatherFun<-function(gath){
gath<-enquo(gath)
gss_cat%>%select(relig,marital,race,partyid)%>%
gather(key,value,-!!gath)%>%
count(!!gath,key,value)%>%
mutate(perc=n/sum(n))
}
但我不知道如何使情节发挥作用。我尝试将!!gath 与ggplot2 一起使用,但没有成功。
GatherFun<-function(gath){
gath<-enquo(gath)
gss_cat%>%select(relig,marital,race,partyid)%>%
gather(key,value,-!!gath)%>%
count(!!gath,key,value)%>%
mutate(perc=n/sum(n))%>%
ggplot(aes(x=value,y=perc,fill=!!gath))+
geom_col()+
facet_wrap(~key, scales = "free") +
geom_text(aes(x = "value", y = "perc",
label = "perc", group = !!gath),
position = position_stack(vjust = .05))
}
【问题讨论】:
-
我对这个最近的问题的回答适用:[将 dplyr SE 与 ggplot2 一起使用] (stackoverflow.com/questions/45279287/use-dplyr-se-with-ggplot2/…)。简而言之,我建议您使用 aes_(x=~value, y=~perc, fill=gath)。当你已经有了 quosures 时,语法比使用 aes_string 更简洁。
标签: r ggplot2 dplyr rlang tidyeval