The object returned by the viewport() function is only a description of a graphics region.
A graphics region is only created on a graphics device when a viewport is “pushed” onto
that device. This is achieved using the pushViewport() function. Each device has only
one “current viewport” (by default this is the entire device), but it maintains a “tree” of
viewports that have been pushed. The current viewport is a node on the viewport tree.
The pushViewport() function adds a viewport as a leaf of the tree – the previous “current
viewport” becomes the parent of this leaf and the new leaf becomes the current viewport.
The popViewport() function prunes the current viewport (and all its children) from the tree
– the parent of the pruned leaf becomes the current viewport. The function upViewport()
acts like popViewport() in terms of setting the current viewport, but does not prune the
previous “current viewport”. The downViewport() function navigates down the tree to a
viewport which has been specified by name (it adds no new viewports to the tree). This
means that there is always only one graphics region to draw into, but it is possible to return
to a previous graphics region through the appropriate set of push/pop/up/down op erations.
As an example, the following code creates a graphics region in the top-left corner of the
page using pushViewport(). This viewport is given the name "vp1". It then does some
drawing and calls upViewport() to return to the root of the viewport tree. Next, it creates
another region in the bottom-right corner of the page (again using pushViewport()) and
do es some drawing there. Finally, it performs an upViewport() to the root of the tree and
a downViewport() to return to the first graphics region and do es some more drawing there
(see Figure 2).
> grid.rect(gp = gpar(lty = "dashed"))
> vp1 <- viewport(x = 0, y = 0.5, w = 0.5, h = 0.5,
+ just = c("left", "bottom"), name = "vp1")
> vp2 <- viewport(x = 0.5, y = 0, w = 0.5, h = 0.5,
+ just = c("left", "bottom"))
> pushViewport(vp1)
> grid.rect(gp = gpar(col = "grey"))
> grid.text("Some drawing in graphics region 1",
+ y = 0.8)
> upViewport()
> pushViewport(vp2)
> grid.rect(gp = gpar(col = "grey"))
> grid.text("Some drawing in graphics region 2",
+ y = 0.8)
> upViewport()
> downViewport("vp1")
> grid.text("MORE drawing in graphics region 1",
+ y = 0.2)
> popViewport()
When several viewports are pushed onto the viewport tree, leaf viewports are located and
sized within the context of their parent viewports. The following code gives an example;
a viewp ort is defined which is one-quarter the size of its parent (half the width and half
the height), and this viewport is pushed twice. The first time it gets pushed the parent is
the root of the viewport tree (which is the entire device) so it is quarter of the size of the
page. The second time the viewport is pushed, it is quarter of the size of its parent viewport.
Figure 3 shows the output of these commands.
2
- 1
- 2
前往页