0

在我之前的问题中,我询问了如何将新点添加到现有的 grob 中,我发现我需要为新点指定一个视口,如果代码在同一环境中运行,这很容易。如果 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视口来添加这些点,这只能通过myplotgrob 获得,在这种情况下,我如何访问视口?

4

1 回答 1

0

grob 只是一个列表,事实证明我可以清楚地从中提取 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()

在此处输入图像描述 在此处输入图像描述

于 2013-10-24T09:50:50.120 回答