To generate complex plots in R, you use a layered graphics system—most commonly the base graphics functions or the ggplot2 package—where you build up a figure from multiple geoms, statistics, and coordinate systems. Base R offers quick, procedural plotting with functions like plot(), lines(), and par(), while ggplot2 provides a grammar-of-graphics approach that makes multi-panel, multi-layer, and annotated plots easier to construct and refine.
Two Main Plotting Systems
R has two dominant plotting paradigms. Base graphics are like a pen-on-paper model: each function call draws directly onto the current device, and you add elements incrementally. This is fast and flexible for simple or highly customized plots, but complex layouts require manual management of margins, axes, and legends. The ggplot2 package (part of the tidyverse) implements Leland Wilkinson's grammar of graphics: you map data variables to aesthetics (x, y, color, size, shape), choose geometric objects (points, lines, bars), and add statistical transformations, scales, and facets. The result is a declarative system where complex plots are built by composing layers rather than issuing drawing commands.
Building a Complex Plot Step by Step
Complex plots typically combine several elements: multiple data series, statistical summaries, annotations, and faceting. Here is a generic workflow using ggplot2:
- Load your data into a data frame and ensure it is in long format if you have multiple series.
- Initialize the plot with
ggplot(data, aes(x = ..., y = ..., color = ...)). - Add geometric layers such as
geom_point(),geom_line(), orgeom_smooth()for trends. - Add statistical summaries with
stat_summary()orgeom_boxplot(). - Use
facet_wrap()orfacet_grid()to create small multiples across groups. - Customize scales, labels, and themes with
scale_color_manual(),labs(), andtheme_minimal(). - Add annotations using
annotate()orgeom_text()for labels and highlights.
Base graphics can achieve similar results with functions like par(mfrow = c(2,2)) for multi-panel layouts, legend(), and text(), but the code tends to be more procedural and less modular.
Common Challenges and Solutions
- Overplotting: When many points overlap, use transparency (
alpha), jittering, or 2D density plots (geom_density_2d()). - Legends and scales: Too many categories can clutter a legend. Consider faceting or combining categories. Use
scale_*_manual()to control colors and labels precisely. - Axis limits and transformations: Use
coord_cartesian()to zoom without dropping data, andscale_y_log10()for log scales. Avoidylim()in ggplot2 as it removes data points outside the range. - Performance with large data: For millions of points, consider aggregating data first, using
geom_hex()orgeom_bin2d(), or switching to base graphics withplot(..., pch = '.')for speed. - Reproducibility: Save plots with
ggsave()specifying dimensions and resolution; for base graphics, usepdf()orpng()devices with explicit width and height.
Extending with Packages
The R ecosystem offers many extensions. The patchwork and cowplot packages arrange multiple ggplot objects into composite figures. ggforce adds specialized geoms like circles and ellipses. plotly converts ggplot objects into interactive web graphics. For network or hierarchical data, igraph and ggraph provide dedicated plotting functions. Spatial data can be mapped with sf and ggplot2 using geom_sf(). These packages let you generate complex, publication-quality figures without writing low-level drawing code.
How to Choose Between Base R and ggplot2
Base graphics are ideal for quick exploratory plots, very large datasets where speed matters, and situations requiring fine-grained control over every element. ggplot2 shines when you need consistent multi-panel layouts, easy grouping and faceting, and a declarative style that reduces code repetition. Many R users start with ggplot2 for most tasks and fall back to base graphics for specific customizations or performance needs. There is no strict rule; both systems are mature and widely documented.
Frequently Asked Questions
Can I combine base R and ggplot2 in one figure?
Yes, using packages like gridExtra or patchwork you can arrange base plots and ggplot objects together, though it requires converting base plots to grid objects (e.g., with gridGraphics). It is more common to use one system per figure for simplicity.
What is the difference between qplot() and ggplot()?
qplot() is a convenience wrapper for quick plots, similar to base plot(). ggplot() is the core function for building plots layer by layer, offering greater flexibility and control for complex graphics.
How do I save a complex plot without losing quality?
Use vector formats like PDF or SVG for scalability, or high-resolution PNG (e.g., 300 dpi) for raster images. In ggplot2, ggsave() handles this; for base graphics, open a device with pdf() or png() and close with dev.off().
Why do my plots look different on screen versus in a saved file?
Screen devices and file devices have different default sizes and resolutions. Always specify dimensions (width, height, units) and resolution (dpi) explicitly when saving to ensure consistency.
Is ggplot2 suitable for very large datasets?
ggplot2 can handle large data but may be slow for millions of points. For such cases, consider aggregating data, using specialized geoms like geom_hex(), or switching to base graphics which are often faster for simple scatter plots.
Can I create 3D plots in R?
Yes, packages like rgl and plotly provide interactive 3D plotting. Base R has persp() for static 3D surfaces. These are useful for visualizing multidimensional data but require careful interpretation.