Multiple ggplots with magrittr tee operator

懵懂的女人 提交于 2019-12-12 08:37:31

问题


I am trying to figure out why the tee operator, %T>%, does not work when I pass the data to a ggplot command.

This works fine

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

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

And this also works fine

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

But when I use the tee operator, as below, it throws "Error: ggplot2 doesn't know how to deal with data of class protoenvironment".

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

Can anyone explain why this final piece of code does not work?


回答1:


Either

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

or abandon the %T>% operator and use an ordinary pipe with the "%>T%" operation made explicit as a new function as suggested in this answer

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

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

As TFlick noted, the reason the %T>% operator doesn't work here is because of the precedence of operations: %any% is done before +.




回答2:


I think your problem has to do with order of operations. The + is stronger than the %T>% operator (according to the ?Syntax help page). You need to pass in the data= parameter to ggplot before you add the geom_point otherwise things get messy. I think you want

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

which uses the functional "short-hand" notation




回答3:


Note that a returned ggplot object is a list with $data field. This can be taken advantaged of. Personally I think the style is cleaner:)

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


来源:https://stackoverflow.com/questions/27264266/multiple-ggplots-with-magrittr-tee-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!