Why can't ggplot2 use %>%?

I mean, it can, if you really want:

`%>%` <- function(lhs, ...){
    pipes <- match.call()    # available from methods
    UseMethod("%>%", lhs) 
}
`%>%.default` <- function(lhs, ...){
    # hacky, but...works
    with(list(`%>%` = magrittr::`%>%`), lhs %>% (pipes[[3]]))
}
`%>%.gg` <- ggplot2:::`+.gg`

1:3 %>% sum %>% seq(1, .) %>% {. > 3}
#> [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

library(ggplot2)

mtcars %>%
    ggplot(aes(mpg, wt)) %>% 
    geom_point() %>% 
    geom_smooth(method = 'lm')

Whether it's a good idea is another matter. ggplot functions are nouns, so adding really makes more sense than piping, which is for passing a noun into a series of verbs. Newer, piped graphics packages frequently use verb names (e.g. plotly::add_lines) so pipes make more sense.

13 Likes