user8491385
user8491385

Reputation: 443

Loop and save ggplot

I have the following code that produces a graph. I want to loop around this code and input different values for the y = (which is currently XYZ). For each ggplot graph I want to save the output. For example first loop would be y = XYZ, second loop y = ABC, third loop y = QRS etc.

UK<-ggplot(Diff, aes(x = FactSet.Fund.Code  , y = XYZ, colour = Fund.Manager.x))
UK<- UK + geom_point(data = subset(Diff,DeskName.x=="UK Equities"), size = 6)
UK<- UK + theme(axis.text = element_text(angle = 90))

Upvotes: 1

Views: 3968

Answers (2)

Sean Lin
Sean Lin

Reputation: 815

Usually ggplots are saved in a list, try below:

Y_list = c('XYZ', 'ABC', 'QRS')
g_list = list()
for (yi in Y_list) {
    UK<-ggplot(Diff, aes_string(x = 'FactSet.Fund.Code', y = yi, colour = 'Fund.Manager.x'))
    UK<- UK + geom_point(data = subset(Diff,DeskName.x=="UK Equities"), size = 6)
    UK<- UK + theme(axis.text = element_text(angle = 90))
    g_list[[yi]] = UK
}

Upvotes: 2

be_green
be_green

Reputation: 753

This should work. Sean is totally right about aes_string making it work. aes normally uses something called non-standard evaluation (if you are unfamiliar, I'd recommend reading here). For your purposes, what it means is that you can't just pass i in the loop below directly to aes, because aes will interpret it as a column, instead of evaluating what information i contains. aes_string just lets you pass in the name of the column as a string. Then you can just save each plot off individually in your loop.

library(ggplot2)


code_list <- list("ABC","XYZ")

Diff <- data.frame(FactSet.Fund.Code = as.character(1:10), 
                   XYZ = rnorm(1:10), ABC = rnorm(1:10))

for(i in code_list){
   ggplot(Diff, aes_string(x = "FactSet.Fund.Code", y = i)) +
              geom_point(size = 6)
  ggsave(paste0(i,".png"))
}

Upvotes: 2

Related Questions