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.
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()
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With