The following code works as designed: a png file is being generated with the desired result.
rr <- createPlot(w[1, "hoofdstuk.nr"], w[1, "paragraaf.nr"], w[1, "paragraaf.titel"], i )
mu <- ddply(rr, "school", summarise, grp.mean=mean(minute))
mypath <- file.path("D:", "work","sf-datascience","avgtimespent", "newplots",paste0("plot", w$hoofdstuk.nr, "-", w$paragraaf.nr, ".png"))
png(file=mypath)
png(paste0("plot", w$hoofdstuk.nr[i], "-", w$paragraaf.nr[i], ".png"), width=800, height=600)
ggplot(rr, aes(x = minute, color = school)) + geom_density() + geom_vline(data=mu, aes(xintercept=grp.mean, color=school),
linetype="dashed") + labs(title=rr[i, "paragraaf.titel"],x="Minute", y = "Density")
dev.off()
However, if I put this in a for loop, only empty png files are being generated. The for loop I use:
for (i in 1:1) {
rr <- createPlot(w[1, "hoofdstuk.nr"], w[1, "paragraaf.nr"], w[1, "paragraaf.titel"], i )
mu <- ddply(rr, "school", summarise, grp.mean=mean(minute))
mypath <- file.path("D:", "work","sf-datascience","avgtimespent", "newplots",paste0("plot", w$hoofdstuk.nr, "-", w$paragraaf.nr, ".png"))
png(file=mypath)
png(paste0("plot", w$hoofdstuk.nr[i], "-", w$paragraaf.nr[i], ".png"), width=800, height=600)
ggplot(rr, aes(x = minute, color = school)) + geom_density() + geom_vline(data=mu, aes(xintercept=grp.mean, color=school),
linetype="dashed") + labs(title=rr[i, "paragraaf.titel"],x="Minute", y = "Density")
dev.off()
}
The dataframe that I am using (w) is not that important I think, because the problem is with the for loop. Also the for loop iterating only once, but still it is not working.
I have searched SO for the problem, but I have only found solutions for printing the ggplot and not generating png file out of it. So the solutions there (print()) are not good for me. Please help me out how to generate png files from ggplot within a for loop?