2013-10-24 33 views
0

在我之前的问题中,我问过如何在现有的grob中添加新的点,我发现我需要为新点指定一个视口,如果代码很简单在相同的环境中运行。如果什么GROB从类似下面的函数返回:从R网格系统中的Grob中提取视口

getgrob = function(x, y) { 
      require(grid) 
      # x = 1:10 
      # y = rnorm(10) 
      plotvp = plotViewport(c(5, 5, 3, 3), name='plotvp') 
      datavp = dataViewport(x, y, name='datavp') 
      datapts = pointsGrob(x, y, pch=20, size=unit(1.3, 'mm'), name='datapts') 
      xaxis = xaxisGrob() 
      yaxis = yaxisGrob() 
      xlab = textGrob('X Label', y=unit(-3, 'lines'), name='xlab') 
      ylab = textGrob('Y Label', x=unit(-3, 'lines'), rot=90, name='ylab') 
      plotbox = rectGrob() 
      dataplot = gTree(children=gList(datapts, 
              xaxis, yaxis, 
              xlab, ylab, 
              plotbox), 
          vp=datavp, name='dataplot') 
      wholeplot = gTree(children=gList(dataplot), 
           vp=plotvp, name='wholeplot') 
      wholeplot 
     } 

myplot = getgrob(1:10, rnorm(10)) 

现在我有一些新的点:

x = 1:10 
y = rnorm(10)/2 

我需要datavp视口,以添加这些点,这是唯一可用通过myplot grob,在这种情况下,我如何访问视口?

回答

0

的格罗只是一个名单,原来我可以说白提取VP元素:

getgrob = function(x, y) { 
    require(grid) 
    x = 1:10 
    y = rnorm(10) 
    plotvp = plotViewport(c(5, 5, 3, 3), name='plotvp') 
    datavp = dataViewport(x, y, name='datavp') 
    datapts = pointsGrob(
         x, y, pch=20, 
         size=unit(2.3, 'mm'), 
         name='datapts', 
         gp=gpar(col='black') 
         ) 
    xaxis = xaxisGrob() 
    yaxis = yaxisGrob() 
    xlab = textGrob('X Label', y=unit(-3, 'lines'), name='xlab') 
    ylab = textGrob('Y Label', x=unit(-3, 'lines'), rot=90, name='ylab') 
    plotbox = rectGrob() 
    dataplot = gTree(children=gList(datapts, 
            xaxis, yaxis, 
            xlab, ylab, 
            plotbox), 
        vp=datavp, name='dataplot') 
    wholeplot = gTree(children=gList(dataplot), 
         vp=plotvp, name='wholeplot') 
    wholeplot 
} 

pdf('/tmp/a.pdf') 
# png('/tmp/a.png') 
mygrob = getgrob(1:10, rnorm(10)) 
grid.draw(mygrob) 
dev.off() 

x = 1:10 
y = rnorm(1:10)/2 
newpoints = pointsGrob(x, y, 
         vp=mygrob$children$dataplot$vp, 
         default.units='native', 
         pch=20, size=unit(2.3, 'mm'), 
         gp=gpar(col='green')) 
mygrob = addGrob(mygrob, newpoints) 

pdf('/tmp/b.pdf') 
# png('/tmp/b.png') 
grid.draw(mygrob) 
dev.off() 

enter image description here enter image description here