1

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))
1
  • 1
    Maybe you need aes_string rather than aes, since you're looping. Saving plots depends on if you want separate png files or one pdf file with multiple pages. Commented Aug 22, 2017 at 15:31

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, first solution looks good although I don't want to save the plot (my miscommunication!) I just want to assign it to an object. So just before the ggsave, the first loop would name the object with the plot as UKXYZ, the second loop would name is UKABC if you get me?
@user8491385 I misunderstood you, please try updated answer.
2

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"))
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.