Search code examples
rplotsjplot

save multiple plots r into separate jpg


Dear Stackoverflow'ers!

I have simple database, app. 130 variables, 1500 records and lots of similar plots to create. I try to avoid save them by hand. The for loop works perfectly for plots (in RStudio).

Here are the data as .csv on dropbox.

data <- read.csv2("data.csv", header=TRUE)
data <- select(data,v1,v2,v3,v4,v5,v6,v7)

for (i in data) {
    sjp.frq(i)
}

I would like to save the plots in some directory as a separate .png or .jpg files. I found some clues here. The code looks like this:

data <- select(df,v1,v2,v3,v4,v5,v6,v7)
variables <- names(data)

for (i in data) {
  png(paste0("plots/plot_",names(data)[i],".png"))
    sjp.frq(i)
  dev.off()
}

I deliberately simplified the sjp.frq expression to not make the code unnessecarely complicated.

And here's the problem. I get only single .png file in folder. Where do I make mistake? There should be seven of them.

Best regards, MaciejB.

PS. I follow the suggestion of making code reproducible and added sample of my databaase. When I use i.e. iris, it works. It seems to be something wrong with my data, some NA's maybe? But when I used na.omit() it's the same.

PS.2 I checked another ploting functions like hist() or plot() but it's the same. Only one plot produced and saved.


Solution

  • This works here!

    data1 <- read.csv2("~/Temp/data.csv", header=TRUE)
    data <- select(data1,v1,v2,v3,v4,v5,v6,v7)
    variables <- names(data)
    dane=1:length(variables)
    for (i in dane ) { #i=2
      png(paste0("Temp/plot_",names(data)[i],".png"))
      sjp.frq(data[,i],title = names(data)[i])
      dev.off()
    }
    

    Here 3 of all plots:

    enter image description here enter image description here enter image description here