使用grid.layout精确定位图

时间:2012-06-17 05:43:54

标签: r lattice r-grid

我有两个格子图。我需要将一个放在另一个之上,我需要它们之间的垂直空间。我的想法是使用grid.layout来指定三行布局,中间行正好是.5“高。然后我可以将一个绘图打印到顶行,另一个绘图打印到底行。

它几乎正常工作。问题是我不能让中间行正好.5“高。这是一个最小的例子:

pdf(file='example.pdf', height=12)

# Create layout and viewports
masterLayout <- grid.layout(
  nrow    = 3, 
  ncol    = 1, 
  heights = unit(c(1, .5, 1), c("null", "inches", "null")),
  respect = matrix(c(0, 1, 0)))
vp1 <- viewport(layout.pos.row=1, just=c("center", "bottom"))  
vp2 <- viewport(layout.pos.row=3, just=c("center", "top"))     

# Create plots
plot1 <- xyplot(1 ~ 1, panel = function () grid.rect(gp=gpar(fill="black")))
plot2 <- xyplot(1 ~ 1, panel = function () grid.rect(gp=gpar(fill="red")))       

# Push viewports and print plots
pushViewport(viewport(layout = masterLayout))
pushViewport(vp1)
print(plot1, newpage = FALSE)
upViewport()
pushViewport(vp2)
print(plot2, newpage = FALSE)

dev.off()

我在这个例子上尝试了很多变化,但是我无法将这些图之间的距离固定在.5“。有没有办法做到这一点?

更新: baptiste的回答如下。另见Deepayan Sarkar在https://stat.ethz.ch/pipermail/r-help/2012-June/316178.html的回答。

1 个答案:

答案 0 :(得分:1)

试试这个:

library(lattice)
# Create layout and viewports
masterLayout <- grid.layout(
  nrow    = 3, 
  ncol    = 1, 
  heights = unit(c(1, .5, 1), c("null", "inches", "null")),
  respect = matrix(c(0, 1, 0)))
vp1 <- viewport(layout.pos.row=1,  name="vp1")  
vp2 <- viewport(layout.pos.row=3,  name="vp2")     
vp3 <- viewport(layout.pos.row=2,  name="spacer")     

theme.novpadding <-
   list(layout.heights =
        list(top.padding = 0,
        main.key.padding = 0,
        key.axis.padding = 0,
        axis.xlab.padding = 0,
        xlab.key.padding = 0,
        key.sub.padding = 0,
        bottom.padding = 0),
        layout.widths =
        list(left.padding = 0,
        key.ylab.padding = 0,
        ylab.axis.padding = 0,
        axis.key.padding = 0,
        right.padding = 0))

# Create plots
plot1 <- xyplot(1 ~ 1, panel = function () grid.rect(gp=gpar(fill="black")),
   scales=list(axs='i',draw=FALSE),
   xlab=NULL,ylab=NULL,par.settings = theme.novpadding)
plot2 <- xyplot(1 ~ 1, panel = function () grid.rect(gp=gpar(fill="red")),
   scales=list(axs='i',draw=FALSE),
   xlab=NULL,ylab=NULL,par.settings = theme.novpadding)       

grid.newpage()
pushViewport(vpTree(viewport(layout = masterLayout,name="master"), vpList(vp1, vp2, vp3)))
seekViewport("master")
print(plot1, draw.in = "vp1")
print(plot2, draw.in = "vp2")
seekViewport("spacer")
grid.rect()

enter image description here