2014-12-03 81 views
7

我想弄清楚为什么tee运算符,%T>%,在我将数据传递给ggplot命令时不起作用。多个ggplots与magrittr tee运算符

这工作得很好

library(ggplot2) 
library(dplyr) 
library(magrittr) 

mtcars %T>% 
    qplot(x = cyl, y = mpg, data = ., geom = "point") %>% 
    qplot(x = mpg, y = cyl, data = ., geom = "point") 

,这也能正常工作

mtcars %>% 
    {ggplot() + geom_point(aes(cyl, mpg)) ; . } %>% 
    ggplot() + geom_point(aes(mpg, cyl)) 

但是,当我使用tee操作,如下,它会抛出“错误:GGPLOT2不知道该如何处理与类原生态环境的数据“。

mtcars %T>% 
    ggplot() + geom_point(aes(cyl, mpg)) %>% 
    ggplot() + geom_point(aes(mpg, cyl)) 

任何人都可以解释为什么这最后一段代码不起作用吗?

回答

5

要么

mtcars %T>% 
    {print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>% 
    {ggplot(.) + geom_point(aes(mpg, cyl))} 

或放弃%T>%经营者和用普通的管道与“%> T% “作为新功能明确作为suggested in this answer

techo <- function(x){ 
    print(x) 
    x 
    } 

mtcars %>% 
    {techo(ggplot(.) + geom_point(aes(cyl, mpg)))} %>% 
    {ggplot(.) + geom_point(aes(mpg, cyl))} 

正如TFlick指出的,%T>%操作符在这里不起作用的原因是由于操作的优先级:%any%+之前完成。

6

我认为你的问题与操作顺序有关。 +%T>%运营商强(根据?Syntax帮助页面)。在添加geom_point之前,您需要将data =参数传递到ggplot否则事情会变得混乱。我想你想

mtcars %T>% 
    {print(ggplot(.) + geom_point(aes(cyl, mpg)))} %>% 
    {ggplot(.) + geom_point(aes(mpg, cyl))} 

其使用功能“速记”符号

+3

您可能需要将第一个ggplot调用打印出来,以便同时调用图形设备。 – 2014-12-03 05:57:35

+0

@TylerRinker我已经解决了这个问题。谢谢! – 2017-02-02 20:37:08

0

请注意,返回的ggplot对象是带有$ data字段的列表。这可以被利用。我个人认为风格比较干净:)

ggpass=function(pp){ 
print(pp) 
return(pp$data) 
} 
mtcars %>% 
    {ggplot() + geom_point(aes(cyl, mpg))} %>% ggpass() %>% 
    {ggplot() + geom_point(aes(mpg, cyl))}