Skip to content
Prev 306094 / 398506 Next

Background color in a grid plot seems to interfere with plot()

Hi
On 24/09/12 09:36, Marius Hofert wrote:
That is a symptom of the conflict that occurs when the 'graphics' 
package and the 'grid' package both try to initialise a new page.
A good rule of thumb is to start a new page with 'graphics' first and 
THEN add 'grid' stuff ('grid' is better at sharing), so a minor 
adjustment to your code would be (#PAUL marks the changes) ...


pdf(file="Rplot.pdf", width=8, height=8, onefile=FALSE)
#PAUL
# Start (empty) new page with 'graphics'
plot.new()
## set up the grid layout
gl <- grid.layout(5, 5, widths=unit(c(1.8, 8, 0.8, 8, 0.8), "cm"),
		  heights=unit(c(0.8, 8, 0.8, 8, 1.5), "cm"))
pushViewport(viewport(layout=gl))
## plot data
par. <- par(no.readonly=TRUE) # save plot settings
for(i in 1:2) { # rows
     i. <- if(i > 1) i+2 else i+1 # jumping over gaps
     for(j in 1:2) { # columns
         j. <- if(j > 1) j+2 else j+1 # jumping over gaps
         pushViewport(viewport(layout.pos.row=i., layout.pos.col=j.))
         grid.rect(gp=gpar(fill="gray90")) # background
         par(plt=gridPLT())
         ## plot
         #PAUL
         # ALWAYS do this before each new 'graphics' plot
         par(new=TRUE)
         plot(1:10, 1:10, log="y", xlab="", ylab="",
              xaxt=if(i==2) "s" else "n", yaxt=if(j==1) "s" else "n")
         upViewport()
     }
}
par(par.)
dev.off()


Hope that helps.

Paul