0

Why does ggplot plot flat lines here and how to make it just loop nicely one plot after the other and save them for futher use:

Var <- list()

mtcars$gear <- as.factor(mtcars$gear)

Var[["list"]][["var_resp"]] <-
  c(
    "mpg"
    ,"hp"
    ,"disp"
    ,"drat"
  )

library(ggplot2)
for (n_var in Var[["list"]][["var_resp"]]) {
  p <- ggplot(mtcars, aes(x = gear, y = n_var)) +
    geom_boxplot()+
    theme(legend.position = "none")
  
  print(p)
}

My original data is in long format, still the same problem

shizzle
  • 89
  • 11

1 Answers1

2

You're passing a character to y which is not supported. You'll need to use either !!sym(n_var) or .data[[n_var]]. Here the latter:

library(ggplot2)
for (n_var in Var[["list"]][["var_resp"]]) {
    p <- ggplot(mtcars, aes(x = gear, y = .data[[n_var]])) +
        geom_boxplot()+
        theme(legend.position = "none")
    
    print(p)
}

Output:

enter image description here

harre
  • 7,081
  • 2
  • 16
  • 28