[英]pipe (%>%) ggplot2 like ggvis
When I integrate tables and figures in a document using knitr
, adding the code makes it more reproducible and interesting.当我使用knitr
在文档中集成表格和图形时,添加代码使其更具可重复性和趣味性。
Often a combination of dplyr
and ggvis
can make a plot that has relatively legible code (using the magrittr
pipe operator %>
).通常dplyr
和ggvis
的组合可以制作具有相对清晰代码的图(使用magrittr
管道运算符%>
)。
mtcars %>%
group_by(cyl, am) %>%
summarise( weight = mean(wt) ) %>%
ggvis(x=~am, y=~weight, fill=~cyl) %>%
layer_bars()
The problem is that the ggvis plot:问题是 ggvis 情节:
does not look quite as as pretty as the ggplot2 plot (I know, factoring of cyl
):看起来不像 ggplot2 情节那么漂亮(我知道, cyl
分解):
However, for ggplot2
we need:但是,对于ggplot2
我们需要:
mtcars %>%
group_by(am, cyl) %>%
summarise( weight = mean(wt) ) %>%
ggplot( aes(x=am, y=weight, fill=cyl) ) +
geom_bar(stat='identity')
My problem is that this switches from %>%
to +
for piping.我的问题是这从%>%
切换到+
进行管道。 I know this is a very minor itch, but I would much prefer to use:我知道这是一个非常小的痒,但我更喜欢使用:
mtcars %>%
group_by(am, cyl) %>%
summarise( weight = mean(wt) ) %>%
ggplot( aes(x=am, y=weight, fill=cyl) ) %>%
geom_bar(stat='identity')
Is there a way to modify the behaviour of ggplot2
so that this would work?有没有办法修改ggplot2
的行为以ggplot2
有效?
ps.附: I don't like the idea of using magrittr
's add()
since this again make the code more complicated to read.我不喜欢使用magrittr
的add()
的想法,因为这再次使代码更难以阅读。
Since it would be too long to expand in the comments, and based on your answer I am not sure if you tried the bit of code I provided and it didn't work or you tried previously and didn't manage由于在评论中展开时间太长,并且根据您的回答,我不确定您是否尝试过我提供的代码但没有用,或者您之前尝试过但没有管理
geom_barw<-function(DF,x,y,fill,stat){
require(ggplot2)
p<-ggplot(DF,aes_string(x=x,y=y,fill=fill)) + geom_bar(stat=stat)
return(p)
}
library(magrittr)
library(dplyr)
library(ggplot2)
mtcars %>%
group_by(cyl, am) %>%
summarise( weight = mean(wt) ) %>%
geom_barw(x='am', y='weight', fill='cyl', stat='identity')
This works for me with: dplyr_0.4.2 ggplot2_2.1.0 magrittr_1.5这对我有用:dplyr_0.4.2 ggplot2_2.1.0 magrittr_1.5
Of course geom_barw
could be modified so you don't need to use the quotes anymore.当然geom_barw
可以修改,所以你不需要再使用引号了。
EDIT : There should be more elegant and safer way with lazy
(see the lazyeval package), but a very quick adaptation would be to use substitute
(as pointed by Axeman - however without the deparse
part):编辑: lazy
应该有更优雅和更安全的方式(请参阅lazyeval包),但非常快速的适应是使用substitute
(如Axeman所指出的-但没有deparse
部分):
geom_barw<-function(DF,x,y,fill,stat){
require(ggplot2)
x<-substitute(x)
y<-substitute(y)
fill<-substitute(fill)
p<- ggplot(DF,aes_string(x=x,y=y,fill=fill))
p<- p + geom_bar(stat=stat)
return(p)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.