How to use quoted variable in ggformula package

90 Views Asked by At

I can use aes_string in ggplot, but how can I use this in ggformula package.

pacman::p_load(ggformula)
plot_list = list()
names_y_axis = names(iris)[2:4]
plot_list = lapply(names_y_axis, \(x){
  gf_point(Sepal.Length ~ x, color = ~ Species)
})
gridExtra::grid.arrange(grobs = plot_list)
#> Error in `FUN()`:
#> ! Problem while computing aesthetics.
#> ℹ Error occurred in the 1st layer.
#> Caused by error in `FUN()`:
#> ! object 'Species' not found
#> Backtrace:
#>      ▆
#>   1. ├─gridExtra::grid.arrange(grobs = plot_list)
#>   2. │ └─gridExtra::arrangeGrob(...)
#>   3. │   └─base::lapply(grobs[toconv], ggplot2::ggplotGrob)
#>   4. │     └─ggplot2 (local) FUN(X[[i]], ...)
#>   5. │       ├─ggplot2::ggplot_gtable(ggplot_build(x))
#>   6. │       │ └─ggplot2:::attach_plot_env(data$plot$plot_env)
#>   7. │       │   └─base::options(ggplot2_plot_env = env)
#>   8. │       ├─ggplot2::ggplot_build(x)
#>   9. │       └─ggplot2:::ggplot_build.ggplot(x)
#>  10. │         └─ggplot2:::by_layer(...)
#>  11. │           ├─rlang::try_fetch(...)
#>  12. │           │ ├─base::tryCatch(...)
#>  13. │           │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers)
#>  14. │           │ │   └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
#>  15. │           │ │     └─base (local) doTryCatch(return(expr), name, parentenv, handler)
#>  16. │           │ └─base::withCallingHandlers(...)
#>  17. │           └─ggplot2 (local) f(l = layers[[i]], d = data[[i]])
#>  18. │             └─l$compute_aesthetics(d, plot)
#>  19. │               └─ggplot2 (local) compute_aesthetics(..., self = self)
#>  20. │                 └─ggplot2:::scales_add_defaults(...)
#>  21. │                   └─base::lapply(aesthetics[new_aesthetics], eval_tidy, data = data)
#>  22. │                     └─rlang (local) FUN(X[[i]], ...)
#>  23. └─base::.handleSimpleError(...)
#>  24.   └─rlang (local) h(simpleError(msg, call))
#>  25.     └─handlers[[1L]](cnd)
#>  26.       └─cli::cli_abort(...)
#>  27.         └─rlang::abort(...)

Created on 2023-04-28 with reprex v2.0.2

1

There are 1 best solutions below

4
On

Consider using either paste or reformulate to create the formula

plot_list = lapply(names_y_axis, \(x){
  # gf_point(as.formula(paste("Sepal.Length ~", x)),
  gf_point(reformulate(x, response = "Sepal.Length"), 
  color = ~ Species, data = iris)
})
gridExtra::grid.arrange(grobs = plot_list)

-output

enter image description here