print(): print a ggplot to a file
To print directly a ggplot to a file, the function print() is used:
# Print the plot to a pdf file
pdf("myplot.pdf")
myplot <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
print(myplot)
dev.off()
For printing to a png file, use:
png("myplot.png")
myplot <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
print(myplot)
dev.off()
ggsave: save the last ggplot
ggsave is a convenient function for saving the last plot that you displayed. It also guesses the type of graphics device from the extension. This means the only argument you need to supply is the filename.
Its also possible to make a ggplot and to save it from the screen using the function ggsave():
# 1. Create a plot
# The plot is displayed on the screen
ggplot(mtcars, aes(wt, mpg)) + geom_point()
# 2. Save the plot to a pdf
ggsave("myplot.pdf")
For saving to a png file, use:
ggsave("myplot.png")
Infos
This analysis has been performed using R software (ver. 3.2.1) and ggplot2 (ver. )