Plot function to change title of plot with changes in x, y arguments - tidyeval?

Hi there -
trying to make a plot function that changes the title to match the arguments.
The intended title in this case is "Boxplot of height by gender".
Or even better, "Boxplot of Height by Gender" - if you can use str_to_title().
Clearly I am doing something wrong.

Any help appreciated.

library(tidyverse)

plot_func <- function(data, cat_var, measure){
  ggplot({{data}}, aes(x = {{cat_var}}, y = {{measure}})) +
    geom_boxplot() +
    labs(title = "Boxplot of {{measure}} by {{cat_var}}")
}

plot_func(starwars, gender, height)
#> Warning: Removed 6 rows containing non-finite values (stat_boxplot).

Created on 2019-11-18 by the reprex package (v0.3.0)

The problem is that you are passing the title parameter as a fixed character string, you have to construct the string programmatically, this would be one way to do it

library(tidyverse)
library(rlang)

plot_func <- function(data, cat_var, measure){
    ggplot({{data}}, aes(x = {{cat_var}}, y = {{measure}})) +
        geom_boxplot() +
        labs(title = str_to_title(paste("Boxplot of", as_string(ensym(measure)), "by", as_string(ensym(cat_var)))))
}

plot_func(starwars, gender, height)

4 Likes

That is cool. Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.