Search code examples
rggplot2rlangforcats

How to supply variable names as strings in fct_reorder within ggplot code?


I want to create the geom_col chart by supplying the variable names as strings. I know the aes_string does that in the ggplot code. However, I am not sure how to handle the variables supplied in the fct_reorder to order the bars. Here is my wip code.

I want to convert this:

mpg %>% 
  ggplot() + 
  geom_col(aes(x = cty, y = fct_reorder(drv, cty, .fun = mean, na.rm = T), fill = drv), width = 0.8) +
  theme_classic()

into a function,

chart_fun <- function(x, y) {
  mpg %>%
    ggplot() +
    geom_col(aes_string(x = x, y = fct_reorder(y, x, .fun = mean, na.rm = T), fill = y), width = 0.8) +
    theme_classic()
}

chart_fun(x = "cty", y = "drv")

but I am getting an error, "Error: 1 components of ... were not used. We detected these problematic arguments: * na.rm Did you misspecify an argument?"

How can I fix this code?


Solution

  • If you want to pass variables as strings you could also make use of the .data pronoun which allows you to stick with aes():

    library(ggplot2)
    library(dplyr)
    library(forcats)
    
    chart_fun <- function(x, y) {
      mpg %>%
        ggplot() +
        geom_col(aes(x = .data[[x]], y = fct_reorder(.data[[y]], .data[[x]], .fun = mean, na.rm = T), fill = .data[[y]]), width = 0.8) +
        theme_classic()
    }
    
    chart_fun(x = "cty", y = "drv")