Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ggplots with magrittr tee operator

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?

like image 268
Tim Cameron Avatar asked Dec 03 '14 05:12

Tim Cameron


People also ask

Which ggplot2 connects multiple operations?

Integrating the pipe operator with ggplot2 We can also use the pipe operator to pass the data argument to the ggplot() function. The hard part is to remember that to build your ggplot, you need to use + and not %>% . The pipe operator can also be used to link data manipulation with consequent data visualization.

What is%>% for?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.

What does %>% do in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

What is Magrittr pipe?

The magrittr pipe operators use non-standard evaluation. They capture their inputs and examines them to figure out how to proceed. First a function is produced from all of the individual right-hand side expressions, and then the result is obtained by applying this function to the left-hand side.


1 Answers

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 +.

like image 85
Hugh Avatar answered Oct 06 '22 08:10

Hugh