Multiple ggplots with magrittr tee operator

前端 未结 3 974
栀梦
栀梦 2021-02-14 23:04

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(dp         


        
相关标签:
3条回答
  • 2021-02-14 23:55

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

    0 讨论(0)
  • 2021-02-15 00:02

    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))}
    
    0 讨论(0)
  • 2021-02-15 00:10

    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

    0 讨论(0)
提交回复
热议问题