Function to save ggplot

老子叫甜甜 提交于 2019-12-02 17:02:57

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", 
 plot = last_plot(), # or give ggplot object name as in myPlot,
 width = 5, height = 5, 
 units = "in", # other options c("in", "cm", "mm"), 
 dpi = 300)

If you would like an image file instead of a pdf, also the following works

ggsave(filename="myPlot.jpg", plot=last_plot())

or with additional parameters, as follows.

ggsave(filename="myPlot.jpg", plot=lastplot(),
       width = 10, height = 5, 
       units = "cm", # other options are "in", "cm", "mm" 
       dpi = 200
       )

Also following file types are supported "eps", "ps", "tex" (pictex), "pdf", "jpeg", "tiff", "png", "bmp", "svg" or "wmf".

If you are using plotnine for ggplot2 in python,

myplot.save(filename="bid_density.png", format='png', \
width = 12, height = 12, units = "in")

Here is a link to the documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!