25.17 Labeling

Here, we label the output with the variable and the bin width that was used in our previous histogram using the rlang::englue()to go under the covers of tidy evaluation. rlang is a low-level package that’s used by just about every other package in the tidyverse because it implements tidy evaluation (as well as many other useful tools). englue() works similarly to str_glue(), so any value wrapped in { } will be inserted into the string.

histogram <- function(df, var, binwidth) {
  label <- rlang::englue("A histogram of {{var}} with binwidth {binwidth}")
  
  df |> 
    ggplot(aes(x = {{ var }})) + 
    geom_histogram(binwidth = binwidth) + 
    labs(title = label)
}

diamonds |> 
  histogram(carat, 0.1)