tidyverse / magrittr

Improve the readability of R code with the pipe
https://magrittr.tidyverse.org
Other
961 stars 157 forks source link

a new operator %g>% for ggplot? #140

Closed superkeyor closed 6 years ago

superkeyor commented 7 years ago

it has been discussed here regarding plotting a ggplot object as a side effect: http://stackoverflow.com/questions/27264266/multiple-ggplots-with-magrittr-tee-operator

Is this possible? Thanks a lot!

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

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

# so it may work also for ggplot like this?
mtcars %g>%
  {ggplot() + geom_point(aes(cyl, mpg))} %>%
  {ggplot() + geom_point(aes(mpg, cyl))}

guess %g>% has to be able to internally trigger a print() command in order to plot a ggplot object

smbache commented 7 years ago

I don't think magrittr should have any package-specific workarounds.

Why not just use helpers, e.g.

qplotter <- function(data, ...) {
  print(qplot(data=data, ...))
  data
}
hadley commented 7 years ago

I think the real problem is that print.ggplot() doesn't invisibly return its first argument.

smbache commented 7 years ago

The above seems to indicate that it is the data they want back for successively producing several plots... but still you're right that print.* should return its argument.

hadley commented 7 years ago

There's also the problem with + vs %>% but that's out of scope.

smbache commented 7 years ago

Yeah, but one can always do gg %>% + geom_*; although not fantastic...