17.2 With the console
# Open the file that will contain your plot (the name is up to you)
pdf(file="myplot.pdf")
# execute the plot
plot(1:10)
# Close the file that will contain the plot
dev.off()
## png
## 2
Formats
R supports a variety of file formats for figures: pdf, png, jpeg, tiff, bmp, svg, ps.
They all come with their own function, for example:
## png
## 2
## png
## 2
The size of the output file can be changed:
# Default: 7 inches (both width and height) for svg, pdf, ps.
svg(file="myfile.svg", width=8, height=12)
plot(1:10)
dev.off()
## png
## 2
# Default: 480 pixels (both width and height) for jpeg, tiff, png, bmp.
png(file="myfile.png", width=500, height=600)
plot(1:10)
dev.off()
## png
## 2
Note that pdf is the only format that supports saving several pages:
## png
## 2
Plot several figures in one page
You can output more than one plot per page using the par() function (sets graphical parameters) and the mfrow argument.
jpeg(file="myfile_multi.jpeg")
# organize the plot in 1 row and 2 columns:
# nr: number of rows
# nc: number of columns
par(mfrow=c(nr=1, nc=2))
plot(1:10)
plot(2:20)
dev.off()
## png
## 2
jpeg(file="myfile_multi4.jpeg")
# organize the plot in 2 rows and 2 columns
par(mfrow=c(nr=2, nc=2))
# top-left
plot(1:10)
# top-right
barplot(table(rep(c("A","B"), c(2,3))))
# bottom-left
pie(table(rep(c("A","B"), c(2,3))))
# bottom-right
hist(rnorm(2000))
dev.off()
## png
## 2