pass function arguments to both dplyr and ggplot

Tidy evaluation is now fully supported in ggplot2 v3.0.0 so it’s not necessary to use aes_ or aes_string anymore.

library(rlang)
library(tidyverse)

diamond_plot <- function (data, group, metric) {
    quo_group  <- sym(group)
    quo_metric <- sym(metric)

    data %>%
        group_by(!! quo_group) %>%
        summarise(price = mean(!! quo_metric)) %>%
        ggplot(aes(x = !! quo_group, y = !! quo_metric)) +
        geom_col()
}

diamond_plot(diamonds, "clarity", "price")

Created on 2018-04-16 by the reprex package (v0.2.0).

Leave a Comment