I have to create some graphs through a loop. The graphs are multipaneled and each panel has three different layers. I tried this code
pdf('plot.pdf', width=14, height=7)
R <- dim(dataset)[1]
for (i in 1:R) {
par(mfrow=c(1,2))
par(mfg=c(1,1))
plot(...)
points(...)
polygon(...)
par(mfg=c(1,2)
plot(...)
points(...)
polygon(....)
}
dev.off()
but the result is a single graph (and not one graph per loop) fully overlaid.
Graph
Is there an issue in looping with the par
function?
EDIT: here's a reproducible example. I tried with split.screen
, but the result is the same single-paged pdf with overlaid plots.
The issue seems related to the pdf
function itself, since the loop does the job correctly.
set.seed(123)
## create data
varA1 <- matrix(rnorm(60,5,1), nrow=3)
varA2 <- matrix(rnorm(60,5,1), nrow=3)
varB1 <- matrix(rnorm(80,20,10), nrow=4)
varB2 <- matrix(rnorm(80,30,20), nrow=4)
sitesA <- 1:nrow(varA1)
sitesB <- 1:nrow(varB1)
totsites <- 1:max(sitesA, sitesB)
## create pdf
pdf('prova.pdf', width=14, height=7)
for(i in totsites) { # the pdf should contain "totsites" number of pages (in this case, 4)
split.screen(c(1,2))
if(i %in% sitesA) {
screen(1)
plot(var1[i,], ylim=c(0, max(c(var1, var2))), col='darkred', type='b', pch=16)
points(var2[i,], col='red', type='b', pch=16)
polygon(c(1:20,rev(1:20)),c(var1[i,]-1,rev(var1[i,]+1)), col=rgb(100, 0, 0, maxColorValue=255, alpha=50), border=NA)
}
if(i %in% sitesB) {
screen(2)
plot(var3[i,], ylim=c(0, max(c(var3, var4))), col='darkgreen', type='b', pch=16)
points(var4[i,], col='green', type='b', pch=16)
polygon(c(1:20,rev(1:20)),c(var3[i,]-10,rev(var3[i,]+10)), col=rgb(0, 100, 0, maxColorValue=255, alpha=50), border=NA)
}
}
dev.off()
BTW, I got this warning
Warning message:
In par(new = TRUE) : calling par(new=TRUE) with no plot