Plot composition

Thomas Lin Pedersen

Key takeaway today

Composing plots are no harder than adding a new layer to your plot

Today

  • Introduce patchwork for plot composition
    • Key design principles
  • From simple to complex layouts
  • The non-panel stuff

Patchwork

  • Composition should have a composable API
  • The API should feel natural and easy to reason about in order to invite experimentation
  • Assume alignment but give escape hatch

Patchwork in a nutshell

p1 <- ggplot(penguins) + 
  geom_point(aes(x = flipper_len, y = bill_len))

p2 <- ggplot(penguins) + 
  geom_histogram(aes(flipper_len))

p1 + p2

Patchwork in a nutshell

p3 <- ggplot(penguins) + 
  geom_boxplot(aes(species, bill_len))

p1 | (p2 / p3)

Patchwork in a nutshell

ggplot(penguins) + 
  geom_point(aes(x = flipper_len, y = bill_len)) + 
  ggplot(penguins) + 
  geom_histogram(aes(flipper_len))

Patchwork in a nutshell

p1 + p2 +
  geom_density(
    aes(flipper_len, after_stat(count))
  )

Exercise

More layout options

p4 <- ggplot(penguins) + 
  geom_bar(
    aes(species, fill = sex), 
    position = "dodge"
  )

wrap_plots(p1, p2, p3, p4, widths = c(1, 2))

More layout options

p1 + p2 + p3 + p4 + plot_layout(widths = c(1, 2))

More layout options

layout <- "
A#B
#CC
DD#
"
p1 + p2 + p3 + p4 + 
  plot_layout(design = layout)

More layout options

layout <- c(
  area(1, 1, 2, 3),
  area(2, 2, 3, 3)
)
p1 + p2 + 
  plot_layout(design = layout)

Exercise

Layout modifiers

  • The composition consists of a grid

  • Panels are placed in one or more neighboring cells

  • Everything outside the panels are placed in the gutter which expands to contain all

  • What if you don’t want that?

Layout modifiers - Insets

p1 + inset_element(
  p2, 
  left = 0.5, 
  bottom = 0.5, 
  right = grid::unit(1, "npc") - grid::unit(6, "mm"),
  top = grid::unit(1, "npc") - grid::unit(6, "mm"),
)

Layout modifiers - Free

p3a <- p3 + 
  guides(x = guide_axis(angle = 45))
p1 + p3a

Layout modifiers - Free

p1 + free(p3a, side = "b")

Layout modifiers - Free

free(p1, "label", side = "b") + p3a

Exercise

Annotations

  • Once composed, the parts will constitute a new graphic