Chapter 14. Output for Presentation

Broadly speaking, visualizations of data serve two purposes: discovery and communication. In the discovery phase, you’ll create exploratory graphics, and when you do this, it’s important to be able try out different things quickly. In the communication phase, you’ll present your graphics to others. When you do that, you’ll need to tweak the appearance of the graphics (which I’ve written about in previous chapters), and you’ll usually need to put them somewhere other than on your computer screen. This chapter is about that last part: saving your graphics so that they can be presented in documents.

Outputting to PDF Vector Files

Problem

You want to create a PDF of your plot.

Solution

There are two ways to output to PDF files. One method is to open the PDF graphics device with pdf(), make the plots, then close the device with dev.off(). This method works for most graphics in R, including base graphics and grid-based graphics like those created by ggplot2 and lattice:

# width and height are in inches
pdf("myplot.pdf", width=4, height=4)

# Make plots
plot(mtcars$wt, mtcars$mpg)
print(ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point())

dev.off()

If you make more than one plot, each one will go on a separate page in the PDF output. Notice that we called print() on the ggplot object to make sure that it will be output even when this code is in a script.

The width and height are in inches, so to specify the dimensions in centimeters, you must do the conversion manually: ...

Get R Graphics Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.