Saving and exporting graphs

In this recipe, you will learn how to save and export our graphs to various useful formats.

How to do it...

To save a graph as an image file format such as PNG, we can use the png() command:

png("scatterplot.png")
plot(rnorm(1000))
dev.off()

The preceding command will save the graph as scatterplot.png in the current working directory. Similarly, if we wish to save the graph as JPEG, BMP, or TIFF, we can use the jpeg(), bmp(), or tiff() commands, respectively.

If you are working in Windows, you can also save a graph using the graphical user interface. First, make your graph, make sure that the graph window is the active window by clicking anywhere inside it, and then navigate to File | Save as | Png or the format of your choice, as shown in the following screenshot:

When prompted to choose a name for your saved file, type in a suitable name and click on Save. As you can see, you can choose from seven different formats.

How it works...

If you wish to use code to save and export your graphs, it is important to understand how the code works. The first step in saving a graph is to open a graphics device suitable for the format of your choice before you make the graph. For example, when you call the png() function, you are telling R to start the PNG graphics device so that the output of any subsequent graph commands you run will be directed to that device.

By default, the display device on the screen is active. So any graph commands result in showing the graph on your screen. However, you will notice that when you choose a different graphics device such as png(), the graphs don't show up on your screen. Finally, you must close the graphics device with the dev.off() command to instruct R to save the graph you plotted in the specified format and write it to disk with the specified filename. If you do not run dev.off(), the file will not be saved.

There's more...

You can specify a number of arguments to adjust the graph as per your needs. The simplest one that we've already used is the filename. You can also adjust the height and width settings of the graph:

png("scatterplot.png",
height=600,
width=600)

The default units for height and width are pixels but you can also specify the units in inches, centimeters, or millimeters:

png("scatterplot.png",
height=4,
width=4,
units="in")

The resolution of the saved image can be specified in dots per inch (dpi) using the res argument:

png("scatterplot.png",
res=600)

If you want your graphs saved in the vector format, you can also save them as a PDF file using the pdf() function:

pdf("scatterplot.pdf")

Besides maintaining a high resolution of your graphs independent of the size, PDFs are also useful because you can save multiple graphs in the same PDF file.

See also

We will cover the details of saving and exporting graphs, especially for publication and presentation purposes in Chapter 15, Finalizing Graphs for Publications and Presentations.