fastread homefastrread library fastread menu

R Programming : Saving Plots

Tutorial by:Maria Ghoste      Date: 2016-06-10 01:54:46

❰ Previous Next ❱

All the graphs 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 some 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.

Saving as 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 jpeg(), png(), bmp() and tiff().

We will use the temperature column of built-in dataset airquality for the remainder of this section as example.

> Temperature <- airquality$Temp

> Temperature
 [1] 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
...
[136] 77 71 71 78 67 76 68 82 64 71 81 69 63 70 77 75 76 68

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()
Saving plot as jpeg in R programming

This will save a jpeg image in the current directory. The resolution of the image by default will be 480x480 pixel.

 

 
 

We can specify the resolution we want with arguments width and height. 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 600x350.

png(file="C:/Programiz/R-tutorial/saving_plot2.png",
   width=600, height=350)
hist(Temperature, col="gold")
dev.off()
Saving plot as png in R programming

Similarly, we can specify the size of our image in inch, cm or mm with the argument units and specify ppi with res. The following code saves a bmp file of size 6x4 inch and 100 ppi.

bmp(file="saving_plot3.bmp",
   width=6, height=4, units="in", res=100)
hist(Temperature, col="steelblue")
dev.off()
Saving plot as bmp in R programming

Finally, if we want to save in the tiff format, we would only change the first line to tiff(filename = "saving_plot3")

Saving as 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. To save a plot as pdf we do the following.

pdf(file="saving_plot4.pdf")
hist(Temperature, col="violet")
dev.off()

Similarly, to save the plot as a postscript file, we change the first line to postscript(file="saving_plot4.ps").

❰ Previous Next ❱


R Programming

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website