Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plots not working in for loop [duplicate]

I need to make a bunch of individual plots and want to accomplish this in a for loop. I am using ggplot2. I would just use the facet option if it could save each graph in a separate file, which I don't think it can do.

There is something going on because the plots are not saved into the files. The files are generated, though, but are empty. Here is an idea of what my code looks like:

for(i in 1:15) {    
pdf(paste("path/plot", i, ".pdf", sep=""), width=4, height=4)

abc <- ggplot(data[data[,3]==i,], 
              aes(variable, value, group=Name, color=Name)) + 
  geom_point(alpha=.6, size=3)+geom_line() + 
  theme(legend.position="none", axis.text.x = element_text(angle = -330)) + 
  geom_text(aes(label=Name),hjust=0, vjust=0, size=2.5) + 
  ggtitle("Title")

abc

dev.off()
}

How can I save the plots into these files?

Note that if I has a numeric value and I run the code inside the for loop, everything works.

like image 203
bill999 Avatar asked Mar 14 '15 19:03

bill999


2 Answers

When I use print it works:

for(i in 1:15) {   
  pdf(paste("plot", i, ".pdf", sep=""), width=4, height=4)
  abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
  print(abc)
  dev.off()
}
like image 137
Mehdi Nellen Avatar answered Nov 03 '22 22:11

Mehdi Nellen


Or try ggsave:

for(i in 1:15) {   
Filename <- paste("plot", i, ".pdf", sep="")
abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
ggsave(filename = Filename, abc, width=4, height=4)
}
like image 6
AndrewMinCH Avatar answered Nov 03 '22 20:11

AndrewMinCH