Search code examples
rggplot2magrittr

Using ggsave with a pipe


I can save a plot with ggsave after I stored it, but using it in a pipeline I get the following error. I wish to plot and save in the same (piped) command.

  no applicable method for 'grid.draw' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')" 

I know ggsave's arguments are first the filename, and then the plot, but switching this in a wrapper does not work. Also, using 'filename=' and 'plot=' in the ggsave command does not work.

library(magrittr)
library(ggplot2)
data("diamonds")

# my custom save function
customSave <- function(plot){
    ggsave('blaa.bmp', plot)
}

#This works:
p2 <- ggplot(diamonds, aes(x=cut)) + geom_bar()
p2 %>% customSave()

# This doesn't work:
ggplot(diamonds, aes(x=cut)) + geom_bar() %>% customSave()

# and obviously this doesn't work either
ggplot(diamonds, aes(x=cut)) + geom_bar() %>% ggsave('plot.bmp')

Solution

  • As akrun pointed out, you need to wrap all of your ggplot in parentheses. You can also use the dot notation to pass an object to a function parameter other than the first in a magrittr pipe stream:

    library(magrittr)
    library(ggplot2)
    data("diamonds")
    
    (
      ggplot(diamonds, aes(x=cut)) +
        geom_bar()
    ) %>% 
      ggsave("plot.png", . , dpi = 100, width = 4, height = 4)