ggplot Graphs as Functions

how-to
Author

Nathan Craig

Published

September 29, 2023

Abstract

Sometimes we need to make several graphs that are very similar in character. Defining the same graph parameters over and over is redundant. In this post we look at making ggplot graphs into functions that can be called repeatedly.

Problem

In many situations, I’ve found myself needing to create many graphs that are identical except for things like the variables displayed and the titles. Writing out the definitions of the graphs over and over, changing only one or two variables in the process, creates a very long and difficult to manage document. It is highly redundant code and becomes difficult to maintain if one wants to make a tweak to the look of all the graphs. All of this mess can be avoided by defining such graphs as a function.

Solution

Using the embrace operator {{}} available since rlang 0.4.0 turning ggplot graphs into functions is pretty straight forward.

library(ggplot2)
data("mtcars")

It is possible to use the embrace operator as an argument for column names and labels defined within functions.

scatter_plot <- function(data, x, y, title) {
  ggplot(data, aes({{x}}, {{y}})) +
    geom_point()+
    labs(title= {{title}})
}
scatter_plot(mtcars, wt, qsec, "Wt by qsec")
scatter_plot(mtcars, drat, hp, "Drat by HP")

Plots can be customized like any ggplot object.

scatter_plot(mtcars, drat, hp, "Drat by HP with trend") +
  geom_smooth()

See Also

Citation

BibTeX citation:
@online{craig2023,
  author = {Craig, Nathan},
  title = {`Ggplot` {Graphs} as {Functions}},
  date = {2023-09-29},
  url = {https://nmc.quarto.pub/nmc/posts/2023-09-29-ggplot-functions},
  langid = {en},
  abstract = {Sometimes we need to make several graphs that are very
    similar in character. Defining the same graph parameters over and
    over is redundant. In this post we look at making ggplot graphs into
    functions that can be called repeatedly.}
}
For attribution, please cite this work as:
Craig, Nathan. 2023. “`Ggplot` Graphs as Functions.” September 29, 2023. https://nmc.quarto.pub/nmc/posts/2023-09-29-ggplot-functions.