Search code examples
rfunctionggplot2boxplot

Trouble with fct_reorder in function


I am trying to create a function that generates boxplots for different columns of data. I wanted to reorder the factors in ascending order of the y-variable. It works when I don't use a function, i.e.,

data(mpg)

ggplot(data = mpg) +
geom_boxplot(aes(fct_reorder(class, hwy), y = hwy))

Which results in this:

enter image description here

But if I try to create a function to examine different variables using the map() function, I get an error:

bp <- function(param){
parameter <- mpg[,param]
ggplot(data = mpg) +
geom_boxplot(aes(fct_reorder(class, parameter)))
}

target_parameters <- c("hwy", "cty")

grid.arrange(grobs = map(target_parameters, bp))

Error in fct_reorder(as.factor(class), parameter) : 
  length(f) == length(.x) is not TRUE

Anybody know what I'm doing wrong?

Thank you so much!


Solution

  • Your function has a couple of issues. Firstly, you are using an argument called parameter, where it should be param. Secondly, you haven't mapped a variable to the y axis (only the x axis). Thirdly, the string is not being converted into a column name inside fct_reorder

    If you want to pass the variable as a string rather than a bare symbol, you can use .data[[param]]

    bp <- function(param){
      ggplot(data = mpg) +
        geom_boxplot(aes(fct_reorder(class, .data[[param]]), .data[[param]]))
    }
    
    bp("hwy")
    

    enter image description here

    This also works within your map example:

    target_parameters <- c("hwy", "cty")
    
    gridExtra::grid.arrange(grobs = map(target_parameters, bp))
    

    enter image description here