在我上一个问题中,我问过如何在现有的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
视口才能添加这些点,这只能通过myplot
grob获得,在这种情况下,我该如何访问视口?
答案 0 :(得分: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()