Reputation: 21
I want to save multiple plots as png using a loop. Unfortunately the loop doesn't seem to work, as the saving and plotting of one single plot works but if I do it within the loop, nothing is saved. I don't receive a error message either. Just nothing happens.
Here is the code that works:
name = main_emo[i]
mypath=file.path("/Users/Jasmin/Documents/Psychologie/Master/Masterarbeit/Working directory", name)
png(mypath)
qplot(x_emo,y_emo, main = main_emo[i]) + geom_errorbar(aes(x=x_emo, ymin=y_emo-sd, ymax=y_emo+sd), width=0.25) + ylab("Rating") + xlab("Emotion")+
theme(panel.grid.major = element_blank()) + scale_y_continuous(breaks=seq(1,7,1)) + expand_limits(y=7)
dev.off()
and this is the loop where it doesn't work anymore:
main_emo <- c("Emotion Profile Funeral", "Emotion Profile Wedding", "Emotion Profile Destroyed Street","Emotion Profile Destroyed Street")
frame_name <- c("nice", "wedd", "des", "fun")
emo_mean <- c("rmean_EM_Trauer_", "rmean_EM_Freude_","rmean_EM_Angst_", "rmean_EM_Aerger_", "rmean_EM_Ekel_", "rmean_EM_Ueber_")
for (i in 1: length(frame_name)) {
y_emo <- c()
sd <- c()
x_emo <- c("Trauer", "Freude", "Angst", "Aerger", "Ekel", "Üeberraschung")
for (j in 1: length(emo_mean)) {
y_col <- unlist(pre_sub[colnames(pre_sub) == paste0(emo_mean[j], frame_name[i])], use.names=FALSE)
y_emo <- c(y_emo, mean(y_col, na.rm=TRUE))
sd <- c(sd, sd(y_col, na.rm=TRUE))
}
name = main_emo[i]
mypath=file.path("/Users/Jasmin/Documents/Psychologie/Master/Masterarbeit/Working directory", name)
png(mypath)
qplot(x_emo,y_emo, main = main_emo[i]) + geom_errorbar(aes(x=x_emo, ymin=y_emo-sd, ymax=y_emo+sd), width=0.25) + ylab("Rating") + xlab("Emotion")+
theme(panel.grid.major = element_blank()) + scale_y_continuous(breaks=seq(1,7,1)) + expand_limits(y=7)
dev.off()
}
Thanks for your help!
Upvotes: 1
Views: 1726
Reputation: 4444
Use ggsave()
Doesn't work:
library("ggplot2")
for (i in unique(diamonds$color)) {
png(paste0("~/Desktop/colour_", i, ".png"))
ggplot(diamonds, aes(carat, price)) + geom_point()
dev.off()
}
Does work:
for (i in unique(diamonds$color)) {
ggplot(diamonds, aes(carat, price)) + geom_point()
ggsave(paste0("~/Desktop/color_", i, ".png"))
}
Upvotes: 1