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.
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)