Application 7: Saving Visualizations

Author

Erik Westlund

Published

June 12, 2025

Saving Visualizations

There are several ways to save visualizations in R, each with its own advantages. Here we’ll cover the most common approaches.

Using ggsave

The ggsave() function is the most straightforward way to save ggplot2 visualizations. It automatically detects the file type from the extension and saves with appropriate settings.

# Basic usage - saves last plot
ggsave("figures/correlation_plot.png", width = 10, height = 8, dpi = 300)

# Save a specific plot
p <- ggplot(data, aes(x = x, y = y)) +
  geom_point() +
  theme_minimal()
ggsave("figures/custom_plot.png", p, width = 10, height = 8, dpi = 300)

# Save with different formats
ggsave("figures/plot.pdf", p, width = 10, height = 8)  # PDF
ggsave("figures/plot.svg", p, width = 10, height = 8)  # SVG
ggsave("figures/plot.jpg", p, width = 10, height = 8, quality = 0.9)  # JPEG

Using Base R Graphics

For base R graphics, you can use functions like png(), pdf(), jpeg(), etc.:

# Save a base R plot
png("figures/base_plot.png", width = 1000, height = 800, res = 100)
plot(1:10, 1:10)
dev.off()

# Save multiple plots to PDF
pdf("figures/multiple_plots.pdf", width = 10, height = 8)
plot(1:10, 1:10)
plot(1:10, 10:1)
dev.off()

Using the Cairo Package

The Cairo package provides high-quality graphics with better font rendering:

# Install and load Cairo
if (!require(Cairo)) install.packages("Cairo")
library(Cairo)

# Save with Cairo
CairoPNG("figures/cairo_plot.png", width = 1000, height = 800, dpi = 100)
plot(1:10, 1:10)
dev.off()

Best Practices

Above all, consider your audience. For example, read the submission guidelines for the academic journal you are targeting. (It’s worth also considering the audience before you overpolish a figure!)

Here are some best practices for saving visuals:

  1. Resolution and Size:
    • For web: 72-96 DPI
    • For print: 300-600 DPI
    • For presentations: 150-200 DPI
  2. File Formats:
    • PNG: Best for web, supports transparency
    • PDF: Best for print, scalable
    • SVG (vector graphics): Best for web, when it works
    • JPEG: Best for photographs, smaller file size

Saving Multiple Plots

To save multiple plots efficiently:

# Save multiple plots to a single PDF
pdf("figures/all_plots.pdf", width = 10, height = 8)
print(p)  # First plot
print(p + theme_dark())  # Second plot
dev.off()

# Save multiple plots to separate files
plots <- list(p1 = p, p2 = p + theme_dark())
for (i in seq_along(plots)) {
  ggsave(
    sprintf("figures/plot_%d.png", i),
    plots[[i]],
    width = 10,
    height = 8,
    dpi = 300
  )
}