In this recipe, we will learn how to save graphs in high-resolution image formats for use in presentations and publications.
We will only use the base graphics functions for this recipe. So, just run the R code at the R prompt. You might wish to save the code as an R script so that you can use it again later.
Let's re-create a simple scatter plot example from Chapter 1, R Graphics, and save it as a PNG file 600 px high and 600 px wide with a resolution of 200 dots per inch (dpi):
png("cars.png",res=200,height=600,width=600) 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) dev.off()
The resulting cars.png
file looks like the following figure:
The pictured graph has a high resolution but the layout and formatting has been lost. So, let's create a high-resolution PNG while preserving the formatting:
png("cars.png",res=200,height=600,width=600) par(mar=c(4,4,3,1),omi=c(0.1,0.1,0.1,0.1),mgp=c(3,0.5,0), las=1,mex=0.5,cex.main=0.6,cex.lab=0.5,cex.axis=0.5) 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()
To save our graph as a high-resolution PNG (200 dpi), we set the res
argument of the png()
function to a value of 200
. The default value of res
is 72
. We also set both the height
and width
arguments to 600
.
In the first example, we can see that simply specifying the resolution and dimensions of the PNG file is not enough. The resultant image loses its original formatting and layout. In addition to specifying the resolution and size, we also need to re-adjust the margins and sizes of various graph elements, including the data points, axes, plot titles, and axis labels. We set these parameters using the par()
function and its arguments as we learned in Chapter 1, R Graphics, and Chapter 3, Beyond the Basics – Adjusting Key Parameters.
To save the graphs as even higher resolution images, we will again need to adjust the relative margins and sizes of the graph components.
3.15.203.124