2013-10-24 36 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