ZetCode

R exporting plots

last modified November 19, 2026

R does not draw a plot on the screen directly. It draws on a graphics device, which may be a window, a PNG file, a PDF document, or an SVG file. The device decides the format, the physical size, and the resolution, and the same plotting code can write to any of them. This article covers the png, pdf, and svg devices, the dev.off call that finishes a file, the list of open devices, and the size and resolution arguments that decide how many pixels a figure has. The examples use R 4.5.2 and write their files to the working directory.

The examples need the ggplot2 package, which is not part of base R. Install it once with install.packages("ggplot2"); the installing packages section of the introduction explains the details.

The PNG device

png opens a file and makes it the current device. Every plotting call after it writes to that file instead of the screen, and dev.off closes the device and completes the file. The arguments width and height are in pixels, and res is the nominal resolution in dots per inch. Because dev.off returns the number of the closed device, the call is usually wrapped in invisible so that the number does not print.

png-device.R
png("scatter.png", width = 600, height = 400, res = 72)
plot(mtcars$wt, mtcars$mpg, pch = 19, col = "steelblue",
     xlab = "Weight (1000 lbs)", ylab = "Miles per gallon")
invisible(dev.off())
cat("size:", file.size("scatter.png"), "bytes\n")
cat("device:", names(dev.cur()), "\n")

The file is 12651 bytes and measures 600 by 400 pixels, which is 8.33 by 5.56 inches at 72 dots per inch. After the device is closed, dev.cur reports the null device, the placeholder that R uses when no file is open. The file is not complete until dev.off runs: a script that stops before that line leaves a truncated PNG, and a long session that never closes devices accumulates open files. This is why the call belongs at the end of every block that opens a device.

Scatter plot of car weight against fuel consumption saved as a PNG
The PNG written by the png device at 600 by 400 pixels.
$ Rscript png-device.R
size: 12651 bytes
device: null device 

The PDF device

pdf writes a vector document: the shapes are stored as instructions rather than pixels, so the figure stays sharp at any zoom level and at any print size. Its width and height are in inches, and there is no resolution argument. By default the device allows several pages in one file, and each plotting call starts a new page.

pdf-device.R
pdf("figures.pdf", width = 6, height = 4)
plot(mtcars$wt, mtcars$mpg, pch = 19, col = "steelblue",
     xlab = "Weight", ylab = "Miles per gallon")
hist(mtcars$mpg, main = "Fuel consumption", xlab = "Miles per gallon")
boxplot(mpg ~ cyl, data = mtcars, xlab = "Cylinders", ylab = "Miles per gallon")
invisible(dev.off())
cat("size:", file.size("figures.pdf"), "bytes\n")

The three calls produce one three-page file of 8102 bytes, with one figure per page. This PDF is smaller than a raster image of the same line art would be, but vector output can grow quickly when a plot contains thousands of points or a photograph, because every mark becomes an instruction. The text in the PDF remains selectable and searchable, which matters for reports that are read on screen. The page size is six by four inches; a later pdf call with a different size starts a new file rather than changing the pages already written.

$ Rscript pdf-device.R
size: 8102 bytes

The SVG device

svg writes the same vector information as XML, the format that web browsers display natively. The file can be opened in a browser, edited in a vector graphics program, or embedded in an HTML page. Like pdf, the device takes its size in inches. The device needs a build of R with cairo support, which the Linux package provides and which capabilities("cairo") reports.

svg-device.R
svg("bars.svg", width = 6, height = 4)
barplot(table(mtcars$cyl), col = "steelblue",
        xlab = "Cylinders", ylab = "Models")
invisible(dev.off())
cat("size:", file.size("bars.svg"), "bytes\n")
cat("first line:", readLines("bars.svg", n = 1), "\n")

The file starts with the XML declaration, which is what a browser expects before the SVG root element, and it is 18053 bytes. The text inside an SVG file is text, not pixels, so the labels stay readable when the page is zoomed and a search can find them. The ggsave function writes SVG only when the svglite package is installed; without that package, open svg, print the plot object, and close the device.

$ Rscript svg-device.R
size: 18053 bytes
first line: <?xml version="1.0" encoding="UTF-8"?> 

Size and resolution

A raster file has two sizes that are easy to confuse: the number of pixels and the physical size in inches. ggsave takes width and height in inches (or in centimetres with units = "cm") and a dpi value, and multiplies them to get the pixel dimensions. Doubling the dpi while keeping the physical size quadruples the number of pixels and makes the file larger.

resolutions.R
library(ggplot2)
png_dimensions <- function(path) {
  con <- file(path, "rb")
  readBin(con, "raw", 16)
  width <- readBin(con, "integer", 1, size = 4, endian = "big")
  height <- readBin(con, "integer", 1, size = 4, endian = "big")
  close(con)
  c(width = width, height = height)
}
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
ggsave("small.png", p, width = 5, height = 3.5, dpi = 72)
ggsave("large.png", p, width = 5, height = 3.5, dpi = 150)
print(png_dimensions("small.png"))
print(png_dimensions("large.png"))
cat("small:", file.size("small.png"), "bytes\n")
cat("large:", file.size("large.png"), "bytes\n")

The helper reads the PNG header directly: after the eight-byte signature and the eight bytes of the first chunk header, the width and the height follow as four-byte big-endian integers. The five-by-three-and-a-half-inch figure is 360 by 252 pixels at 72 dpi and 750 by 525 at 150 dpi, and the larger file is more than twice the size. The physical size is the same in both files; only the pixel count changes. For a printed page 150 to 300 dpi is usually enough, and for a web page 72 to 96 dpi keeps the download small.

$ Rscript resolutions.R
 width height 
   360    252 
 width height 
   750    525 
small: 4497 bytes
large: 10548 bytes

Managing open devices

R can keep several devices open at once, and each new device becomes the current one. dev.list shows the open devices with their numbers and names, and dev.cur shows the current device. dev.off closes only the current device, so a script that opens two files must close both; the idiom below closes devices until only the null device remains.

devices.R
png("one.png", width = 400, height = 300)
plot(1:5, pch = 19)
pdf("two.pdf", width = 4, height = 3)
plot(1:5, pch = 19)
print(dev.list())
cat("current:", names(dev.cur()), "\n")
while (dev.cur() > 1) invisible(dev.off())
cat("open devices:", length(dev.list()), "\n")
cat("current:", names(dev.cur()), "\n")

The PNG device is number 2 and the PDF device is number 3, and the PDF is current because it was opened last. The loop closes the PDF and then the PNG, after which no device is open and dev.cur reports the null device. dev.list returns NULL rather than an empty vector at that point, so its length is zero. In an interactive session a forgotten device can hide a plot behind another window; dev.off() at the prompt closes the current one and returns to the previous device.

$ Rscript devices.R
png pdf 
  2   3 
current: pdf 
open devices: 0 
current: null device 

A complete example

The final script draws the same figure three times. A single function holds the plotting code, so the only difference between the files is the device that receives the output. This is the usual shape of an export script: compute the data once, draw it once, and save it in every format that the destination needs.

export.R
draw <- function() {
  plot(mtcars$wt, mtcars$mpg, pch = 19, col = "steelblue",
       xlab = "Weight (1000 lbs)", ylab = "Miles per gallon",
       main = "Weight and fuel consumption")
  abline(lm(mpg ~ wt, data = mtcars), col = "firebrick", lwd = 2)
}
png("export.png", width = 600, height = 400)
draw()
invisible(dev.off())
pdf("export.pdf", width = 6, height = 4)
draw()
invisible(dev.off())
svg("export.svg", width = 6, height = 4)
draw()
invisible(dev.off())
sizes <- file.size(c("export.png", "export.pdf", "export.svg"))
print(sizes)
cat("total:", sum(sizes), "bytes\n")

The three files have the same content and very different sizes: 20612 bytes for the PNG, 6527 for the PDF, and 47016 for the SVG. The SVG is the largest here because it stores every point, line, and glyph as markup, while the PDF compresses its instructions more tightly. The PNG is a fixed grid of pixels that cannot be enlarged without blurring. For the web a PNG or SVG is the usual choice, for print a PDF, and for a figure that a designer will edit an SVG. The printed sizes also give a quick check that all three files were written; a missing file would appear as NA.

Scatter plot with a fitted line exported as a PNG
The PNG version of the figure that is also written as PDF and SVG.
$ Rscript export.R
[1] 20612  6527 47016
total: 74155 bytes

Next steps

The ggplot2 customization article covers the labels, themes, and scales that make an exported figure readable, and the base graphics article shows the plotting functions used in the examples here. The ggplot2 article explains how the same figures are built from layers and saved with ggsave. The next article in the series introduces S3 classes, the object system that plot and many other functions already use.

Source

R documentation: png

R documentation: pdf

R documentation: svg

R documentation: dev.off and dev.list

ggplot2 reference: ggsave

In this article we have written plots to PNG, PDF, and SVG files and closed each device with dev.off. We compared a raster format with two vector formats, read the pixel dimensions from a PNG header, and changed the resolution while keeping the physical size. We listed and closed several open devices, and the final script exported one figure in all three formats. The series continues with R S3 classes.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.