What if we want to pass in different variables?

  • Instead of writing out the entire aes(), the user can just pass in the variable names
  • But there’s a catch!

This doesn’t work:

my_function <- function(x_var) {
  aes(x = x_var)
}
my_function(abc)
Aesthetic mapping: 
* `x` -> `x_var`
#> Aesthetic mapping: 
#> * `x` -> `x_var`

We can “embrace” the argument to tell ggplot2 to “look inside” the argument and use its value, not its expression

my_function <- function(x_var) {
  aes(x = {{x_var}})
}
my_function(abc)
Aesthetic mapping: 
* `x` -> `abc`
#> Aesthetic mapping: 
#> * `x` -> `abc`

New version of the piechart function:

piechart <- function(data, var) {
  ggplot(data, aes(factor(1), fill = {{ var }})) +
    geom_bar(width = 1) + 
    coord_polar(theta = "y") + 
    xlab(NULL) + 
    ylab(NULL)
}
mpg |> piechart(class)