Skip to content

Instantly share code, notes, and snippets.

@mccarthy-m-g
Last active December 22, 2022 21:21
Show Gist options
  • Save mccarthy-m-g/db17b984b583d6e2d74e9b3781c39f79 to your computer and use it in GitHub Desktop.
Save mccarthy-m-g/db17b984b583d6e2d74e9b3781c39f79 to your computer and use it in GitHub Desktop.

Summary

This code takes an alternative approach to the fancy patchwork hacking hacking Andrew Heiss used to get to shared x- and y-axis labels in a patchwork plot.

https://fediscience.org/@andrew/109558941216921694

Code

library(ggplot2)
library(patchwork)

huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))
h <- ggplot(huron, aes(year))

h1 <- h +
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "grey70") +
  geom_line(aes(y = level))

h2 <- h + geom_area(aes(y = level))

# Get a shared x-axis
h_patch <- h1 + h2 & xlab(NULL) & theme(plot.margin = margin(5.5, 5.5, 0, 5.5))
wrap_elements(panel = h_patch) +
  labs(tag = "year") +
  theme(
    plot.tag = element_text(size = rel(1)),
    plot.tag.position = "bottom"
  )

# Get a shared y-axis
h_patch <- h1 / h2 & ylab(NULL) & theme(plot.margin = margin(5.5, 5.5, 5.5, 0))
wrap_elements(h_patch) +
  labs(tag = "level") +
  theme(
    plot.tag = element_text(size = rel(1), angle = 90),
    plot.tag.position = "left"
  )

Created on 2022-12-22 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment