Search code examples
rggplot2magrittr

Plot and process ggplot2 object in same expression


I would like to build up my GGplot graph and plot the steps in between. Is this possible to do without first assigning and then plotting?

p0 <- ggplot(mtcars, aes(mpg, cyl)) + geom_point()
p0
p1 <- p0 + scale_x_sqrt()
p1
p2 <- p1 + facet_wrap(~gear)
p2

Something like

ggplot(mtcars, aes(mpg, cyl)) + geom_point() %P>%
 + scale_x_sqrt() %P>%
 + facet_wrap(~gear)

Which produces three plots but returns nothing


Solution

  • Sure thing!

    `%P+%` <- function(p1, p2) {p <- ggplot2:::`+.gg`(p1, p2); print(p); invisible(p)}
    

    And the call

    ggplot(mtcars, aes(mpg, cyl)) %P+% 
      geom_point() %P+%
      scale_x_sqrt() %P+%
      facet_wrap(~gear)
    

    will get you three plots in a row. The only limitation is that you have to be careful around mixing regular + and %P+% because of precedence issues.