Reputation: 1074
I have the following data and code
data <- data.frame(trt = c("A", "A", "B", "B", "B", "B", "B", "A", "A", "A"), group = c("G1", "G1", "G1", "G1", "G1", "G2", "G2", "G2", "G2", "G2"), value = c(6.4, 7.2, 6.5, 6.6, 6.2, 7.2, 8.5, 7.3, 7.1, 6.9))
for(i in c(1:2)) {
savePDFPath <- paste("/Path/Plot/G", i, ".pdf", sep = "")
pdf(file = savePDFPath)
dd <- subset(data, group == paste("G", i, sep = ""))
ggplot(dd, aes(trt, value)) + geom_boxplot()
dev.off()
}
After I execute this code, 2 pdf files are saved in the folder. Nevertheless, I cannot open the files. It shows `the file Gx.pdf could not be opened. What goes wrong in my code? Thank you.
Upvotes: 1
Views: 349
Reputation: 60060
I'm not 100% sure why the error is occurring but I'm able to fix it by explicitly printing the plot:
for(i in c(1:2)) {
savePDFPath <- paste("Plots/G", i, ".pdf", sep = "")
pdf(file = savePDFPath)
dd <- subset(data, group == paste("G", i, sep = ""))
p <- ggplot(dd, aes(trt, value)) + geom_boxplot()
print(p)
dev.off()
}
Upvotes: 0
Reputation: 671
Try using ggsave()
to save the plot as pdf. I've tried the following code and it works.
for(i in c(1:2)) {
savePDFPath <- paste("/Path/Plot/G", i, ".pdf", sep = "")
dd <- subset(data, group == paste("G", i, sep = ""))
ggplot(dd, aes(trt, value)) + geom_boxplot()
ggsave(savePDFPath)
}
Upvotes: 1