Saving your graphs
Of course, you will need to save many of the graphs that you create. The simplest method is to click inside the graph and then copy as a metafile or copy as a bitmap. You can then save your graph in a Word document or within a PowerPoint presentation. However, you may wish to save your graphs as JPEGS, PDFs, or in other formats.
Now we shall create a PDF of a graph (a histogram that we will create using the
hist()
command, which you will come across later in this book). First we get ready to create a PDF (in R, we refer to this procedure as opening the PDF device driver) using the command pdf()
, and then we plot. Finally, we complete the job (closing the device driver) using the command dev.off()
.
You may wish to save your plot to a particular directory or folder. To do so, navigate to File | Change Dir in R and select the directory or folder that you wish to use as your R working directory. For example, I selected a directory called BOOK
, which is located within the following filepath on my computer:
C:\Users\David\Documents\BOOK
To confirm that this folder is now my current working folder, I entered the following command:
getwd()
The output obtained is as follows:
[1] "C:/Users/David/Documents/BOOK"
R has confirmed that its working folder is the one that I wanted. Note that R uses forward slashes for filepaths. Now, we create a vector of data and create our histogram as follows:
y <- c(7, 18, 5, 13, 6, 17, 7, 18, 28, 7,17,28) pdf("My_Histogram.pdf") hist(y, col = "darkgreen") dev.off()
A PDF of your histogram should be saved in your R working directory. It is called My_Histogram.pdf
and it looks like the following:
The graphing options available in R include
postscript()
, pdf()
, bitmap()
, and
jpeg()
. For a complete list of options, navigate to Help | Search help and enter the word devices
. The list you need is labelled List of graphical devices
.
For example, to create a postscript plot of the histogram, you can use the following syntax:
postscript(file="myplot.ps") hist(y, col = "darkgreen") dev.off()
To create and save a JPEG image from the current graph, use the
dev.copy()
command:
dev.copy(device=jpeg,file="picture.jpg") dev.off()
Your image is saved in the R working directory.
You can save and recall a plot that is currently displayed on your screen. If you have a plot on your screen, then try the following commands:
x = recordPlot() x
You can delete your plot but get it back again later in your session using the following command:
replayPlot(x)