Skip to content

Instantly share code, notes, and snippets.

@kelly-sovacool
Last active August 11, 2023 14:38
Show Gist options
  • Save kelly-sovacool/c7fb93f863a8c69f5f4707a95bd09fe2 to your computer and use it in GitHub Desktop.
Save kelly-sovacool/c7fb93f863a8c69f5f4707a95bd09fe2 to your computer and use it in GitHub Desktop.
How to write a function to add multiple ggproto objects to a ggplot
#' ---
#' output:
#' md_document:
#' pandoc_args:
#' - '--from=markdown-implicit_figures'
#' - '--to=commonmark'
#' - '--wrap=preserve'
#' ---
#+ reprex-setup, include = FALSE
options(tidyverse.quiet = TRUE)
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", error = TRUE)
knitr::opts_knit$set(upload.fun = knitr::imgur_upload)
#+ reprex-body
library(tidyverse)
dat1 <- tibble(a = 1:3, b = 1:3)
dat2 <- tibble(l = c(2))
plot_hline1 <- function(ggplot_obj, yint, dat = dat2) {
ggplot_obj +
geom_hline(data = dat, aes(yintercept = {{ yint }})) +
theme_classic()
}
plot_hline2 <- function(yint, dat = dat2) {
geom_hline(data = dat, aes(yintercept = {{ yint }})) +
theme_classic()
}
plot_hline3 <- function(yint, dat = dat2) {
list(geom_hline(data = dat, aes(yintercept = {{ yint }})),
theme_classic()
)
}
# 🚫 fails with pipe to pass the ggplot object
ggplot(dat1, aes(a, b)) +
geom_point() %>%
plot_hline1(yint = l)
# 🚫 fails adding ggproto objects
ggplot(dat1, aes(a, b)) +
geom_point() +
plot_hline2(yint = l)
# ✅ works when you use a list of ggproto objects
ggplot(dat1, aes(a, b)) +
geom_point() +
plot_hline3(yint = l)
#' <sup>Created on `r Sys.Date()` by the [reprex package](https://reprex.tidyverse.org) (v`r utils::packageVersion("reprex")`)</sup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment