In this recipe, we will learn how to save graphs in vector formats such as PDF, SVG, and PostScript (PS), which are resolution-independent.
Once again we will use the basic graph functions. So, just make sure that you have started R and type in the code at the R prompt.
Let's use the same scatter plot example from the previous recipe and save it in different vector formats, starting with PDF:
pdf("cars.pdf") plot(cars$dist~cars$speed, main="Relationship between car distance and speed", xlab="Speed (miles per hour)",ylab="Distance travelled (miles)", xlim=c(0,30),ylim=c(0,140), xaxs="i",yaxs="i", col="red",pch=19,cex=0.5) dev.off()
Similarly, we can save the graph as SVG or PS using the svg()
and postscript()
functions, respectively:
svg("3067_10_03.svg") #plot command here dev.off() postscript("3067_10_03.ps") #plot command here dev.off()
The vector format export commands are similar to the image format commands we saw in the previous recipe. First, we open a new device by calling the pdf()
, svg()
, or postscript()
functions with the output filename as its only argument, then issue the plot command, and finally close the device with dev.off()
.
As vector formats are resolution-independent, you can zoom in or out of them without losing any clarity of the graph. Size does not affect the resolution. So, unlike the image formats in the previous recipe, we did not have to re-adjust the graph margins and component sizes to save the graph as PDF, SVG, or PS.
We can save more than one graph in a single PDF file by setting the onefile
argument to TRUE
(the default value). This is a useful output for presentations. All we have to do is issue the pdf()
command with the output file name, then issue all the plot commands in the desired order, and close the device with dev.off()
. For example, let's make three variations of the cars plot with three different colors for the data points and save them into one file:
pdf("multiple.pdf") for(i in 1:3) plot(cars,pch=19,col=i) dev.off()
Another important setting when saving graphs in vector formats is the color model. Most publications require authors to use the CMYK (Cyan Magenta Yellow Key) color model in their graphs, instead of the default RGB (Red Green Blue) model. We can save our graphs as PDFs or postscripts with the CMYK color model simply by setting the colormodel
argument to cmyk
:
pdf("multiple.pdf",colormodel="cmyk") for(i in 1:3) plot(cars,pch=19,col=i) dev.off()
By default, colormodel
is set to rgb
. The other possible value is gray
for grayscale.
3.133.129.97