0

I have a few functions which are called by a final function to draw ggplot graph. I am using a list to pass to function call so that the graph could be iterated through each of them. However, the xlab is not showing correctly.

first_plot <- function(dta, vari) {
  vari <- enquo(vari)
  dta %>%
    group_by(!!vari) %>%
    summarize(a = mean(!!whatever) +
    ggplot(aes(x=!!vari)) +
    geom_point(aes(a)) 
}

plot_all <- function(dta, item) {
  list_var <- list(name = item)
  plot_list<- list()
  for(i in 1:length(item)) {
    vari <- sym(item[i])
    plot_list[[i]] <- first_plot(dta, vari) 
  }
}

If I pass plot_all(data, c('a','b','c'), I would expect the xlab would show a, b, c correspondingly but it always show vari. Can you help me to troubleshoot this?

Thanks.

Yi Du
  • 455
  • 2
  • 8
  • 17
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Show exactly how you are calling this function. Also make sure the syntax is correct. You seem to be missing a `)` in `first_plot` – MrFlick Aug 16 '19 at 20:01
  • You can try to add `xlab(quo_name(vari))` – kath Aug 16 '19 at 20:27
  • I tried but didn't work. – Yi Du Aug 16 '19 at 20:41

1 Answers1

0

Looks like you need as.name instead of enquo in first_plot. Then the !! will work when creating the plot. A simplified example with iris data:

library(ggplot2)
library(cowplot)

first_plot <- function(dta, vari) {
  vari <- as.name(vari)
  ggplot(dta, aes(y = !!vari, x=Species)) +
    geom_point()
}

first_plot(iris, "Sepal.Length")
plot_list <- lapply(names(iris)[1:4], first_plot, dta=iris)
plot_grid(plotlist=plot_list)

Should make this plotenter image description here

teofil
  • 2,344
  • 1
  • 8
  • 17