Reputation: 13520
I am trying to generate a series of plots using a for loop like the following:
varList = list("Var1","Var2","Var3")
plot_list = list()
for (i in 1:3) {
gg = ggplot(data_set,aes(x=log(varList[[i]])),fill=factor(RETAINED)))
gg = gg + geom_density(alpha=.3) + labs(x = varList[[i]],y="Density")
gg = gg + ggtitle(paste("Distribution of ",varList[[i]],sep=" "))
plot_list[[i]] = gg
}
The varList[[i]] works fine for labs() and ggtitle but unfortunately when I am trying the same thing got log() function in aes() it does not work out and it gives me the following error:
Error while parsing the string.
If I replace arList[[i]] with for example Var1 everything works fine and there is no problem but that way I will only have the same figure over and over again. I am wondering if there is a way to convert this string to a variable and I have tried the followings:
And none of the above led me to the correct answer. Any help would be much appreciated.
Thanks
Upvotes: 3
Views: 673
Reputation: 13520
I solved my problem using Gregor and Roland comments and suggestions as following:
varList = list("Var1","Var2","Var3")
plot_list = list()
for (i in 1:3) {
gg = ggplot(data_set,aes(xfill=factor(RETAINED)))
gg = gg + aes_string(x = sprintf("log(%s)", varList[[i]]))
gg = gg + geom_density(alpha=.3) + labs(x = varList[[i]],y="Density")
gg = gg + ggtitle(paste("Distribution of ",varList[[i]],sep=" "))
plot_list[[i]] = gg
}
Upvotes: 2