Save ggplot with a function

You can use print() to save plots produced from ggplot2 to a file.

First, define your function to save plots:

savePlot <- function(myPlot) {
        pdf("myPlot.pdf")
        print(myPlot)
        dev.off()
}

Create your plot:

 myPlot <- ggplot(ggplot(data=df.music, aes(x=music, y=number)) +
 geom_bar(stat="identity") +
 xlab(colnames(df.music)[1]) +
 ylab(colnames(df.music)[2]) +
 ylim(c(0,11)) +
 ggtitle("Ulubiony typ muzyki wśród studentów")

And finally call the function:

savePlot(myPlot)

Alternatively, you could just use ggsave() after creating your plot:

ggsave(filename="myPlot.pdf", plot=myPlot)

Following was useful for me, may be for someone else as well. One can save the last plot without explicitly referring it as well.

ggsave("filename.pdf",  # jpg, png, eps, tex, etc.
       plot = last_plot(), # or an explicit ggplot object name,
       width = 7, height = 5, 
       units = "in", # other options c("in", "cm", "mm"), 
       dpi = 300)