Data Science Desktop Survival Guide
by Graham Williams |
|||||
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 that it is tall.
ggsave("myplot.pdf", 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 22. 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 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 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.
|