8

I'm trying to write many graphs to one olocation, but instead its writing a bunch of blank pictures:

my code looks like:

titleplot<-NULL
for(i in 1:99){
  titleplot<-colnames(data[i])
  mypath <- file.path("C:","Users","user.ME","Desktop","graph outputs", paste("myplot_", titleplot, ".jpg", sep = ""))
  plot(data[,i],type="l", main =titleplot)
  jpeg(file=mypath)
  dev.off()
}

Does anyone know why this would happen or how I can remedy this?

user124123
  • 1,642
  • 7
  • 30
  • 50

4 Answers4

11

You are supposed to put your jpeg command before you call your plot command.

jpeg(file=mypath)
plot(...)
dev.off()
asb
  • 4,392
  • 1
  • 20
  • 30
8

Combination of the answers from Mohammed Shaker and asb gives this really simple code:

for (i in dev.list()[1]:dev.list()[length(dev.list())]) {
   dev.off()
}

This removes all open graphics devices:

> dev.list()
NULL
GMSL
  • 355
  • 2
  • 11
  • ...and if you are troubleshooting after hitting the device limit, be sure to restart R: `.rs.restartR()` to clear your dev.list(), otherwise you may have corrected your code but still hit the device limit again. – DirtStats Feb 15 '21 at 18:59
  • Shorter : `for (i in seq_along(dev.list())) dev.off()` – Julien Jun 18 '23 at 09:00
3

I had this problem before. If you type dev.list() in the R console, you will see all plots you tried to save. For example:

# tiff jpeg tiff jpeg tiff jpeg tiff jpeg tiff tiff tiff tiff tiff jpeg tiff tiff tiff 
# 2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17 18  

No matter where you put dev.off() in your code, you get this problem by the time if you do save many plots. One possible solution for this problem is to restart the R session.

This may be done in the command line: .rs.restartR() or by pressing ctrl+shift+F10.

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39
  • 4
    There is no reason to believe that this happens if you plot too many things. You open a device, remember to close it. That's all there is to it. Which is why where you put your device opening statements is important. Not only that, you may end up getting the wrong plots in the wrong files if you are not careful with the order in which you put your statements. A lot of times restarting the R session is a no go if costly analyses have been run. – asb May 12 '16 at 07:47
  • Years later, apologies for just seeing it now. Comment is for "the archives" so to speak. A new plot device is opened whenever calling par(), if a plot device does not already exist, if an improper function is trying to check plot dimensions for example. In an R-shiny server, each thread/user would open a device, and could be another cause of the error. Not sure how thread limit and device limit co-mingle. – jmw86069 Sep 22 '22 at 16:54
-2

Just keep print dev.off() till there is no open device

SaintTail
  • 6,160
  • 4
  • 31
  • 51
0o0o0o0
  • 35
  • 6