Saving Graphs to Files

The R graphics display can consist of various graphics devices. The default device is the screen. If you want to save a graph to a file, you must set up another device.

Let’s go through the basics of R graphics devices first to introduce R graphics device concepts, and then discuss a second approach that is much more direct and convenient.

Let’s open a file:

> pdf("d12.pdf")

This opens the file d12.pdf. We now have two devices open, as we can confirm:

> dev.list()
X11 pdf
  2   3

The screen is named X11 when R runs on Linux. (It’s named windows on Windows systems.) It is device number 2 here. Our PDF file is device number 3. Our active device is the PDF file:

> dev.cur()
pdf
  3

All graphics output will now go to this file instead of to the screen. But what if we wish to save what’s already on the screen?

One way to save the graph currently displayed on the screen is to reestablish the screen as the current device and then copy it to the PDF device, which is 3 in our example, as follows:

> dev.set(2)
X11
  2
> dev.copy(which=3)
pdf
  3

But actually, it is best to set up a PDF device as shown earlier and then rerun whatever analyses led to the current screen. This is because the copy operation can result in distortions due to mismatches between screen devices and file devices.

Note that the PDF file we create is not usable until we close it, which we do as follows:

> dev.set(3)
pdf
  3
> dev.off()
X11
  2

You can also close the device by exiting R, if you’re finished working with it. But in future versions of R, this behavior may not exist, so it’s probably better to proactively close.