11.59 Save Plot to File

20200820 Generating a plot is one thing but we will want to make use of the plot possibly in multiple ways. Once we have a plot displayed we can save the plot to file quite simply using ggplot2::ggsave(). The format is determined automatically by the name of the file to which we save the plot. Here, for example, we save the plot as a pdf that we might include in other documents or share with a colleague for discussion. Using width=11 and height=7, the plot will be wider than it is tall.

ggsave("myplot.pdf", width=11, height=7)

Other formats supported include svg, png, and jpg.

If the ggplot2::ggplot() has been saved into a variable, perhaps p, then it can be referred to when saving:

ggsave("myplot.pdf", plot=p, width=11, height=7)

The default values for width= and height= are those of the current plotting window. Specifying them explicitly overrides the current window dimensions. By trial and error or by experience we find the dimensions that suit our requirements.

There is some art required in choosing a good width and height as discussed in Chapter 28. By increasing the height or width any text that is displayed on the plot essentially stays the same size. Thus by increasing the plot size the text will appear smaller. By decreasing the plot size the text becomes larger. Experimentation can help get the right size for any particular purpose.

The function ggplot2::ggsave() is a wrapper around various other R functions that save plots to files, and adds some value to these default plotting functions.

A more traditional approach to saving a plot is to initiate a graphic device such as grDevices::pdf(), print the plot as below where we assume the plot is saved in the template variable p, and then close the device with grDevices::dev.off().

pdf("myplot.pdf", width=11, height=7)
p
dev.off()

For a grDevices::pdf() device the default width= and height= are 7 (inches). Thus, for both of the above examples we are widening the plot whilst retaining the height.



Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0