Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

r - Print to PDF in a for loop

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 plot 3 different plots from the iris dataset. Then it should save it to the C:/ drive. The PDF files are created, but are corrupted.

for(i in 1:3){
  pdf(paste("c:/", i, ".pdf", sep=""))
  plot(cbind(iris[1], iris[i]))
  dev.off()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...