Multiple ggplots with the magrittr tee operator

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

It works great

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 it also works great

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

But when I use the tee operator, as shown below, it throws "Error: ggplot2 does not know how to handle the class proton environment data."

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

Can someone explain why this last piece of code is not working?

+7
r ggplot2 magrittr
source share
3 answers

Or

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

or abandon the %T>% operator and use a regular pipe with the operation "%> T%" 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 does not work here is due to the priority of the operations: %any% runs to + .

+5
source share

I think your problem is with the order of operations. + stronger than the %T>% operator (according to ?Syntax help page). You need to pass the data = parameter to ggplot before adding geom_point , otherwise everything will become messy. I think you want

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

which uses a functional short notation

+6
source share

Note that the returned ggplot is a list with the $ data field. It can be beneficial. 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))} 
0
source share

All Articles