Multiple layers with ggplot2

STAT1003 – Statistical Techniques

Dr. Emi Tanaka

Australian National University

These slides are best viewed on a modern browser like Google Chrome on a desktop or laptop. Some interactive components may require some time to fully load.

Layering plots

  • You can add more than one layer.
  • The order of layer matters.
  • A layer inherits the data and mapping from the initialised ggplot object by default

Layer-specific data and aesthetic mapping

  • For each layer, aesthetic and/or data can be overwritten.

Case study 🚜 Iowa farmland values by county

Drawing maps

  • Drawing maps require spatial/boundary data that defines the shapes of the regions.

Layer specific aesthetic

  • Layer specific aesthetic are not inherited by other layers.

Layer specific data

  • Layer specific data can overwrite the inherited data.

Layer specific data as a function of inherited data

Annotation layer

  • annotate() allows you to add elements to plots without a data.frame

More features of ggplot2

  • theme() to modify non-data components of the plot
  • facet_wrap() and facet_grid() for small multiples
  • scale_*() to modify scales
  • guides() to modify legends
  • labs() to modify labels and titles
  • ggsave() to save plots to files
  • … etc.

ggplot2 extensions

https://www.ggplot2-exts.org/

Featuring: ggincerta

  • Your tutor, Maggie Ma, developed an extension package ggincerta to visualise uncertainty in ggplot2 as part of her PhD work!
library(ggincerta)
ggplot(nc) + 
  aes(fill = duo(value, sd)) +
  geom_sf()

Summary

  • You can construct plots with multiple layers in ggplot2.
  • The order of the layer matters.

  • A layer inherits the data and mapping from the initialised ggplot object by default
  • But the data and mappings for each layer can be overwritten.
  • There are many more features and extensions of ggplot2 to explore!