Saving a Plot in R
In this article, you’ll learn to save plots in R programming. You’ll learn to save plots as bitmap and vector images.
All the graphs (bar plot, pie chart, histogram, etc.) we plot in R programming are displayed on the screen by default.
We can save these plots as a file on disk with the help of built-in functions.
It is important to know that plots can be saved as bitmap image (raster) which are fixed size or as vector image which are easily resizable.
How to save plot as a bitmap image?
Most of the image we come across like jpeg or png are bitmap image. They have a fixed resolution and are pixelated when zoomed enough.
Functions that help us save plots in this format are
We will use the temperature column of built-in dataset
airquality for the remainder of this section as example.
> Temperature <- airquality$Temp > Temperature  67 72 74 62 56 66 65 59 61 69 74 69 66 68 58 64 66 57 68 62 59 73 61 61 57 58 57 ...  77 71 71 78 67 76 68 82 64 71 81 69 63 70 77 75 76 68
Save as Jpeg image
To save a plot as jpeg image we would perform the following steps.
Please note that we need to call the function
dev.off() after all the plotting, to save the file and return control to the screen.
jpeg(file="saving_plot1.jpeg") hist(Temperature, col="darkgreen") dev.off()
This will save a jpeg image in the current directory. The resolution of the image by default will be
Save as png image
We can specify the resolution we want with arguments
We can also specify the full path of the file we want to save if we don’t want to save it in the current directory.
The following code saves a png file with resolution
png(file="C:/Datamentor/R-tutorial/saving_plot2.png", width=600, height=350) hist(Temperature, col="gold") dev.off()
Save as bmp image
Similarly, we can specify the size of our image in inch, cm or mm with the argument
units and specify ppi with
The following code saves a bmp file of size
6x4 inch and
bmp(file="saving_plot3.bmp", width=6, height=4, units="in", res=100) hist(Temperature, col="steelblue") dev.off()
Save as tiff image
Finally, if we want to save in the tiff format, we would only change the first line to
tiff(filename = "saving_plot3")
tiff(file="saving_plot3.tiff", width=6, height=4, units="in", res=100) hist(Temperature, col="steelblue") dev.off()
How to save plot as a vector image?
We can save our plots as vector image in pdf or postscript formats.
The beauty of vector image is that it is easily resizable. Zooming on the image will not compromise its quality.
Save as pdf file
To save a plot as pdf we do the following.
pdf(file="saving_plot4.pdf") hist(Temperature, col="violet") dev.off()
Save as postscript file
Similarly, to save the plot as a postscript file, we change the first line to
postscript(file="saving_plot4.ps") hist(Temperature, col="violet") dev.off()