R ggplot2 - Save Plot (ggsave)
The `ggsave()` function provides a streamlined approach to exporting ggplot2 visualizations. At its simplest, you specify a filename and the function handles the rest.
Key Insights
ggsave()automatically detects output format from file extension and intelligently sizes plots based on the last displayed plot or explicit plot object- Vector formats (PDF, SVG, EPS) scale without quality loss and are ideal for publications, while raster formats (PNG, JPEG, TIFF) require careful DPI and dimension management
- Fine-tuning parameters like
dpi,width,height, andunitsensures plots render consistently across different output contexts, from presentations to academic journals
Basic Usage and Automatic Detection
The ggsave() function provides a streamlined approach to exporting ggplot2 visualizations. At its simplest, you specify a filename and the function handles the rest.
library(ggplot2)
# Create a sample plot
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Fuel Efficiency vs Weight",
x = "Weight (1000 lbs)",
y = "Miles per Gallon",
color = "Cylinders") +
theme_minimal()
# Save as PNG (format detected from extension)
ggsave("fuel_efficiency.png", plot = p)
# Save as PDF
ggsave("fuel_efficiency.pdf", plot = p)
# Save as SVG
ggsave("fuel_efficiency.svg", plot = p)
When you omit the plot argument, ggsave() saves the last displayed plot. This works well in interactive sessions but creates fragile code in scripts.
# Not recommended for production code
ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point()
ggsave("output.png") # Saves last plot - risky in scripts
Controlling Dimensions and Units
Plot dimensions significantly impact readability and layout. The width, height, and units parameters give you precise control.
# Specify dimensions in inches (default)
ggsave("plot_inches.png",
plot = p,
width = 8,
height = 6)
# Use centimeters for international publications
ggsave("plot_cm.png",
plot = p,
width = 20,
height = 15,
units = "cm")
# Millimeters for precise control
ggsave("plot_mm.png",
plot = p,
width = 200,
height = 150,
units = "mm")
# Wide format for presentations
ggsave("plot_wide.png",
plot = p,
width = 16,
height = 9) # 16:9 aspect ratio
Different output contexts demand different dimensions:
# Journal article (typical single column)
ggsave("journal_single.pdf",
plot = p,
width = 3.5,
height = 3.5)
# Journal article (double column)
ggsave("journal_double.pdf",
plot = p,
width = 7,
height = 5)
# Presentation slide
ggsave("presentation.png",
plot = p,
width = 10,
height = 7.5)
# Poster
ggsave("poster.pdf",
plot = p,
width = 36,
height = 48)
Resolution and DPI Settings
DPI (dots per inch) determines image quality for raster formats. Higher DPI produces sharper images but larger file sizes.
# Screen display (72-96 DPI sufficient)
ggsave("screen.png",
plot = p,
width = 8,
height = 6,
dpi = 96)
# Print quality (300 DPI standard)
ggsave("print.png",
plot = p,
width = 8,
height = 6,
dpi = 300)
# High-quality publication (600 DPI)
ggsave("publication.tiff",
plot = p,
width = 7,
height = 5,
dpi = 600)
# Web optimization (lower DPI, smaller file)
ggsave("web.png",
plot = p,
width = 8,
height = 6,
dpi = 72)
DPI only affects raster formats. Vector formats (PDF, SVG, EPS) ignore this parameter since they scale infinitely without quality loss.
# DPI ignored for vector formats
ggsave("vector.pdf",
plot = p,
width = 8,
height = 6,
dpi = 300) # dpi parameter has no effect
Format-Specific Parameters
Different formats support different compression and quality settings through the device parameter and additional arguments.
# PNG with specific background
ggsave("transparent.png",
plot = p,
width = 8,
height = 6,
bg = "transparent")
# JPEG with quality control (1-100)
ggsave("compressed.jpg",
plot = p,
width = 8,
height = 6,
dpi = 300,
quality = 90) # Higher = better quality, larger file
# TIFF with compression
ggsave("compressed.tiff",
plot = p,
width = 8,
height = 6,
dpi = 300,
compression = "lzw")
For PDF output, you can specify the paper size and other PDF-specific options:
# PDF with specific paper size
ggsave("letter.pdf",
plot = p,
width = 8.5,
height = 11)
# A4 paper size
ggsave("a4.pdf",
plot = p,
width = 8.27,
height = 11.69)
Scaling and Text Rendering
The scale parameter multiplies all plot elements, useful for adjusting text and point sizes without recreating the plot.
# Base plot
base_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(size = 2) +
labs(title = "Default Scale") +
theme_minimal(base_size = 11)
# Normal scale
ggsave("normal_scale.png",
plot = base_plot,
width = 6,
height = 4,
scale = 1)
# Increase all elements by 50%
ggsave("scaled_up.png",
plot = base_plot,
width = 6,
height = 4,
scale = 1.5)
# Decrease all elements by 25%
ggsave("scaled_down.png",
plot = base_plot,
width = 6,
height = 4,
scale = 0.75)
Batch Export Workflow
For reproducible research or automated reporting, save multiple plots with consistent settings:
# Define standard export settings
export_settings <- list(
width = 8,
height = 6,
dpi = 300,
units = "in"
)
# Create multiple plots
plots <- list(
scatter = ggplot(mtcars, aes(wt, mpg)) + geom_point(),
histogram = ggplot(mtcars, aes(mpg)) + geom_histogram(bins = 10),
boxplot = ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot()
)
# Export all plots
for (name in names(plots)) {
ggsave(
filename = paste0("output_", name, ".png"),
plot = plots[[name]],
width = export_settings$width,
height = export_settings$height,
dpi = export_settings$dpi,
units = export_settings$units
)
}
For multiple formats of the same plot:
formats <- c("png", "pdf", "svg")
base_name <- "analysis_plot"
for (fmt in formats) {
ggsave(
filename = paste0(base_name, ".", fmt),
plot = p,
width = 8,
height = 6,
dpi = if (fmt == "png") 300 else NULL
)
}
Device-Specific Customization
The device parameter accepts custom device functions for advanced control:
# Use Cairo for better font rendering
ggsave("cairo.png",
plot = p,
device = "png",
type = "cairo",
width = 8,
height = 6,
dpi = 300)
# Custom device function
ggsave("custom.png",
plot = p,
device = function(filename, ...) {
png(filename,
type = "cairo-png",
antialias = "subpixel",
...)
},
width = 8,
height = 6,
dpi = 300)
Troubleshooting Common Issues
Font rendering problems often occur when exporting to PDF:
# Embed fonts in PDF for better compatibility
library(extrafont)
loadfonts(device = "pdf")
ggsave("with_fonts.pdf",
plot = p,
width = 8,
height = 6,
device = cairo_pdf)
For plots with many points, file size can balloon:
# Reduce point density for web
web_plot <- ggplot(mtcars, aes(wt, mpg)) +
geom_point(size = 1) + # Smaller points
theme_minimal()
ggsave("optimized.png",
plot = web_plot,
width = 8,
height = 6,
dpi = 96, # Lower DPI for web
limitsize = FALSE)
The ggsave() function provides comprehensive control over plot export, balancing convenience with precision. Understanding the interplay between dimensions, DPI, and format selection ensures your visualizations render correctly across all output contexts.