Syntax/grammar question with ggsave()

#this question is more about a syntax choice than a technical issue, so this code chunk is more of a formality
library(ggplot2)
mt_plot <- ggplot() + 
  geom_point(data = mtcars, aes(x=mpg, y = disp)) 

ggsave("mt_plot.png", mt_plot, dpi = 300, height = 4, width = 6)

ggsave() has as its first argument the filename to be saved to, rather than the gg object itself. This seems different than other canonical "export"-type functions, like write_csv() and everything like it, where the object to be exported is always the first argument in the export function to match the "pipeable" grammar of the tidyverse. In the example chunk above, I can't just stack the call to ggsave at the end of a pipeline, I have to start a new "sentence" specifically to save the plot.

Why is the export syntax different for ggsave(), such that piping into ggsave() doesn't work? Is it to be closer to base R's plot export functions (png/pdf/etc)? Does it have something to do with the "+" symbol that makes piping not work the same way? Does it have to do with a grammar choice to separate creating a plot and exporting that plot?

Hi, is this what you are aiming for? Since it is part of the ggplot2 syntax (as you guessed correctly) you don't use a pipe here but a +:

library(ggplot2)
ggplot() + 
  geom_point(data = mtcars, aes(x=mpg, y = disp)) +
  ggsave("mt_plot.png", dpi = 300, height = 4, width = 6)

Created on 2020-07-10 by the reprex package (v0.3.0)

A simple explanation I guess may be that ggplot2 was written years before the what became the other tidyverse packages. ggplot2 therefore only has one foot inside the tidyverse, but is too established to change.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.