Print to PDF in a for loop

后端 未结 2 1666
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 01:07

I want to loop over a plot and put the result of the plot in a PDF.

The following code is used to do this:

What this does is loop 3 times and pl

相关标签:
2条回答
  • 2020-12-08 01:26

    To drawn lattice plots on the device, one needs to print the object produced by a call to one of the lattice graphics functions. Normally, in interactive use, R auto prints objects if not assigned. In loops however, auto printing does not work, so one must arrange for the object to be printed, usually by wrapping it in print().

    Here is an example (please excuse my abuse of the formula notation ;-):

    require(lattice)
    for(i in 1:3) {
        pdf(paste("plot", i, ".pdf", sep = ""))
        print(xyplot(iris[,1] ~ iris[,i], data = iris))
        dev.off()
    }
    

    This produces the three plots on a pdf device.

    0 讨论(0)
  • 2020-12-08 01:53

    Is a file name that contains "c:/" a valid file name on your OS? That looks like part of the working directory that you'd want to set before calling pdf. I get an error telling me it can't open that file:

    Error in pdf(paste("c:/", i, ".pdf", sep = "")) : 
      cannot open file 'c:/1.pdf'
    

    If I drop the "c:/" bit from the file name, three PDFs are generated properly. Also, if you move the dev.off() outside of the for loop, you'll get a single PDF with three pages instead of three PDFs. May or may not be what you want...

    for(i in 1:3){
      pdf(paste("plot", i,".pdf",sep=""))
      plot(cbind(iris[1],iris[i]))
      dev.off()
    }
    
    0 讨论(0)
提交回复
热议问题