Question

I just tried my first steps with grid. I would like to set up a 2 x 2 matrix of square scatter plots, with some space in between. To get the space, I actually use a 3 x 3 layout (Question 1: is there an easier way?). As you can see from the example below, the points are plotted outside the bounding rectangle. I somehow have to specify the limits in the plot. Question 2: How can this be done? Finally, can I use base graphics to create the plots? [I know lattice graphics will work and also a standard layout could be used (or ggplot2), but I am interested if that's possible with grid.layout, too]

require(grid)

## generate data to be plotted in the top left plot
X <- matrix(rexp(2000), ncol=2)

## plot device
file <- "foo.pdf"
pdf(file=file, width=10, height=10)

## set up grid.layout
gl <- grid.layout(3, 3, respect=rbind(c(0,1,0), c(1,1,1), c(0,1,0)),
                  widths=unit(c(3,1,3), "inches"), heights=unit(c(3,1,3), "inches")) # define grid layout

pushViewport(viewport(layout=gl)) # use this layout in a viewport

## (1,1) plot
pushViewport(viewport(layout.pos.row=1, layout.pos.col=1, name="11"))
grid.points(X[,1], X[,2], pch=1) # points
grid.rect() # bounding rectangle
grid.xaxis() # x-axis
grid.yaxis() # y-axis
grid.text(expression(italic(X[1])), y=unit(-3, "lines")) # x-axis label
grid.text(expression(italic(X[2])), x=unit(-3, "lines"), rot=90) # y-axis label
grid.text("Plot 1", x=0.86, y=0.9, gp=gpar(fontface="bold", cex=1.6)) # add label
upViewport()

## (1,2) plot
pushViewport(viewport(layout.pos.row=1, layout.pos.col=3, name="13"))
grid.rect()
upViewport()

## (2,1) plot
pushViewport(viewport(layout.pos.row=3, layout.pos.col=1, name="31"))
grid.rect()
upViewport()

## (2,2) plot
pushViewport(viewport(layout.pos.row=3, layout.pos.col=3, name="33"))
grid.rect()
upViewport()

## plot device
dev.off()
Was it helpful?

Solution

You need to have the correct coordinate system: either convert your data to "npc" units, or set up a viewport with native units derived from your data,

pushViewport(dataViewport(X[,1], X[,2], 
               layout.pos.row=1, layout.pos.col=1, name="11"))

works as expected.

Regarding question 1, have a look at the gtable package on github; it is being developed to facilitate this sort of things for ggplot2 and other grid-based graphic frameworks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top