1

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

它几乎可以工作了。问题是我不能让中间行正好是 0.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()

我在这个例子中尝试了很多变化,但我无法将绘图之间的距离固定为 0.5"。有没有办法做到这一点?

更新:下面巴蒂斯特的回答很好。另见 Deepayan Sarkar 在https://stat.ethz.ch/pipermail/r-help/2012-June/316178.html的回答。

4

1 回答 1

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()

在此处输入图像描述

于 2012-06-17T20:35:48.490 回答