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.
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:
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().
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.
If you find this curated material useful then you can consider a donation to support it's ongoing availability and give you access to the PDF version of this book. The material has been scoped up by Generative AI without permission or any kind of recompense so do consider a donation if you can afford it. Unlike Generative AI your access to this materials is freely given. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Togaware has a 30 year tradition of making popular open source software which includes sold privacy preserving productivity apps, 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