Save multiple plots in loop in R

折月煮酒 提交于 2020-06-17 02:43:25

问题


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!


回答1:


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"))
}


来源:https://stackoverflow.com/questions/55687061/save-multiple-plots-in-loop-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!