How to Save Graphics to an Image File in R
If you want to publish your results, you have to save your plot to a file in R and then import this graphics file into another document. Much of the time however, you may simply want to use R graphics in an interactive way to explore your data.
To save a plot to an image file, you have to do three things in sequence:
Open a graphics device.
The default graphics device in R is your computer screen. To save a plot to an image file, you need to tell R to open a new type of device — in this case, a graphics file of a specific type, such as PNG, PDF, or JPG.
The R function to create a PNG device is png(). Similarly, you create a PDF device with pdf() and a JPG device with jpg().
Create the plot.
Close the graphics device.
You do this with the dev.off() function.
Put this in action by saving a plot of faithful to the home folder on your computer. First set your working directory to your home folder (or to any other folder you prefer). If you use Linux, you’ll be familiar with using “~/” as the shortcut to your home folder, but this also works on Windows and Mac:
> setwd("~/") > getwd()  "C:/Users/Andrie"
Next, write the three lines of code to save a plot to file:
> png(filename="faithful.png") > plot(faithful) > dev.off()
Now you can check your file system to see whether the file faithful.png exists. (It should!) The result is a graphics file of type PNG that you can insert into a presentation, document, or website.