How to save the generated graphics files (in png) within a loop

Asked

Viewed 66 times

2

I’m trying to generate png files of graphics that are inside a loop. I tried to do with the function ggsave but I cannot insert inside the loop and outside the loop generates the empty file.


ggsave(paste0(dados [i], ".png"), path = "C:/Users/")

# Create data: 
set.seed(1)
dados <-as.data.frame(matrix (sample ( 0:100, 102 , replace=T) , ncol=17, byrow=TRUE))
colnames(dados) <- c ("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17")

# To use the fmsb package, I have to add 2 lines to the dataframe: the max and min of each topic to show on the plot!
dados <- rbind(rep(100,17) , rep(0,17) , dados)

# Prepare title
mytitle <- c()

# Loop for each plot
for(i in 1:6){
  # Custom the radarChart !
  radarchart( dados[c(1,2,i+2),], axistype=1, 
              #custom polygon
              pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4  , 
              
              #custom the grid
              cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,50,100), cglwd=0.6,
              
              #custom labels
              vlcex=0.9,
              
              #title
              title=mytitle[i],         
  )
} 
  • Hello, that would be R that?

  • Hello, yes in R. I will generate 770 charts and would like them to be saved in files, automating the process. Thank you!

1 answer

2

Add the png line with the location where you want to save(you have to have write permission so change as in the example below to your image folder)

At the end of your chart generation add dev.off()

Code

...

for(i in 1:6){

  png(filename = paste0('C:\\Users\\SEU USUARIO\\Pictures\\',i,'.png'))

  radarchart( dados[c(1,2,i+2),], axistype=1, 
              #custom polygon
              pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4  , 
              
              #custom the grid
              cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,50,100), cglwd=0.6,
              
              #custom labels
              vlcex=0.9,
              
              #title
              title=mytitle[i],         
  )
  dev.off()
}  
  • 2

    It worked, thank you very much for your reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.