Question

I am doing a loop operation which reads from the same column of two dataframes (obs & sim)and produces scatter plots. . There are 24 columns in total in each data frame. The following script works fine.

for(i in 1:24) {
  plot (obs[,i],sim[,i],xlab="obs",ylab="sim",main=substitute(paste('Lead Time (hrs) = ', a), list(a=i)))
}

But I want to save each and every plots in a folder (C:/RPlots/) and I want to include this operation also in the loop.

I used the following script , but it didn't work

for(i in 1:24) {
  jpeg('C:/RPlots/paste("myplot_", c(i), ".jpg")')
  plot (obs[,i],sim[,i],xlab="obs",ylab="sim",main=substitute(paste('Lead Time (hrs) = ', a), list(a=i)))
  dev.off()
}

Can anyone help me?

Était-ce utile?

La solution

you got an error in jpeg call

try this

for(i in 1:24) {
jpeg(paste0("C:/RPlots/myplot_",i,".jpg")) 
plot (obs[,i],sim[,i],xlab="obs",ylab = "sim",
      main = substitute(paste('Lead Time (hrs) = ', a), list(a = i))) 
dev.off() 
}

Autres conseils

You can use paste, paste0, or sprintf to create the names, but it is simpler to just use an integer format in the file argument.

For example if you start the jpeg device with a command like:

jpeg('C:/RPlots/myplot_%03d.jpg')

before the loop, then create multiple plots in the loop, then the first plot will be saved in file myplot_001.jpg, the second in myplot_002.jpg, the third in myplot_003.jpg, etc.

The "%03d" is the important part, the 3 means you want 3 digit numbers and the 0 means pad them with a 0. Adjust for your preferences.

As mentioned by @Greg Snow, if you cannot place the jpeg() function outside of the loop for whatever reason, there is sprintf() of C library fame:

paste0("C:/RPlots/myplot",sprintf("%03d",i),".jpg")

Here, i is an integer from a for loop iterator. This sets the leading zero padding, which is nice if you want to later iterate over these images with ffmpeg, etc.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top