The Grid Graphics Package

The Grid Graphics Package [R logo]

Help pages for package `grid' version 2.4.1

A C D E F G H L M P R S T U V W X Y

-- --

grid-package The Grid Graphics Package

-- A --

absolute.size | Absolute Size of a Grob
addGrob | Add a Grid Graphical Object
applyEdit | Create and Apply Edit Objects
applyEdits | Create and Apply Edit Objects
arcCurvature | Draw a Curve Between Locations
arrow | Describe arrows to add to a line.
arrowsGrob | Draw Arrows

-- C --

childNames | Create a Grid Graphical Object
circleGrob | Draw a Circle
clipGrob | Set the Clipping Region
convertHeight | Convert Between Different grid Coordinate Systems
convertNative | Convert a Unit Object to Native units
convertUnit | Convert Between Different grid Coordinate Systems
convertWidth | Convert Between Different grid Coordinate Systems
convertX | Convert Between Different grid Coordinate Systems
convertY | Convert Between Different grid Coordinate Systems
current.transform | Get the Current Grid Viewport (Tree)
current.viewport | Get the Current Grid Viewport (Tree)
current.vpPath | Get the Current Grid Viewport (Tree)
current.vpTree | Get the Current Grid Viewport (Tree)
curveGrob | Draw a Curve Between Locations

-- D --

dataViewport | Create a Viewport with Scales based on Data
downViewport | Maintaining and Navigating the Grid Viewport Tree
draw.details | Customising grid Drawing
drawDetails | Customising grid Drawing

-- E --

editDetails | Customising grid Editing
editGrob | Edit the Description of a Grid Graphical Object
engine.display.list | Control the Grid Display List

-- F --

frameGrob Create a Frame for Packing Objects

-- G --

gEdit | Create and Apply Edit Objects
gEditList | Create and Apply Edit Objects
get.gpar | Handling Grid Graphical Parameters
getGrob | Get a Grid Graphical Object
getNames | List the names of grobs on the display list
gList | Create a Grid Graphical Object
gpar | Handling Grid Graphical Parameters
gPath | Concatenate Grob Names
Grid | Grid Graphics
grid.add | Add a Grid Graphical Object
grid.arrows | Draw Arrows
grid.circle | Draw a Circle
grid.clip | Set the Clipping Region
grid.collection | Create a Coherent Group of Grid Graphical Objects
grid.convert | Convert Between Different grid Coordinate Systems
grid.convertHeight | Convert Between Different grid Coordinate Systems
grid.convertWidth | Convert Between Different grid Coordinate Systems
grid.convertX | Convert Between Different grid Coordinate Systems
grid.convertY | Convert Between Different grid Coordinate Systems
grid.copy | Make a Copy of a Grid Graphical Object
grid.curve | Draw a Curve Between Locations
grid.display.list | Control the Grid Display List
grid.draw | Draw a grid grob
grid.edit | Edit the Description of a Grid Graphical Object
grid.frame | Create a Frame for Packing Objects
grid.get | Get a Grid Graphical Object
grid.grab | Grab the current grid output
grid.grabExpr | Grab the current grid output
grid.grill | Draw a Grill
grid.grob | Create a Grid Graphical Object
grid.layout | Create a Grid Layout
grid.line.to | Move or Draw to a Specified Position
grid.lines | Draw Lines in a Grid Viewport
grid.locator | Capture a Mouse Click
grid.move.to | Move or Draw to a Specified Position
grid.newpage | Move to a New Page on a Grid Device
grid.pack | Pack an Object within a Frame
grid.place | Place an Object within a Frame
grid.plot.and.legend | A Simple Plot and Legend Demo
grid.points | Draw Data Symbols
grid.polygon | Draw a Polygon
grid.polyline | Draw Lines in a Grid Viewport
grid.pretty | Generate a Sensible Set of Breakpoints
grid.prompt | Prompt before new page
grid.record | Encapsulate calculations and drawing
grid.rect | Draw rectangles
grid.refresh | Refresh the current grid scene
grid.remove | Remove a Grid Graphical Object
grid.segments | Draw Line Segments
grid.set | Set a Grid Graphical Object
grid.show.layout | Draw a Diagram of a Grid Layout
grid.show.viewport | Draw a Diagram of a Grid Viewport
grid.text | Draw Text
grid.xaxis | Draw an X-Axis
grid.xspline | Draw an Xspline
grid.yaxis | Draw a Y-Axis
grob | Create a Grid Graphical Object
grobHeight | Create a Unit Describing the Width of a Grob
grobName | Generate a Name for a Grob
grobWidth | Create a Unit Describing the Width of a Grob
grobX | Create a Unit Describing a Grob Boundary Location
grobY | Create a Unit Describing a Grob Boundary Location
gTree | Create a Grid Graphical Object

-- H --

heightDetails Width and Height of a grid grob

-- L --

linesGrob | Draw Lines in a Grid Viewport
lineToGrob | Move or Draw to a Specified Position

-- M --

moveToGrob Move or Draw to a Specified Position

-- P --

packGrob | Pack an Object within a Frame
placeGrob | Place an Object within a Frame
plotViewport | Create a Viewport with a Standard Plot Layout
pointsGrob | Draw Data Symbols
polygonGrob | Draw a Polygon
polylineGrob | Draw Lines in a Grid Viewport
pop.viewport | Pop a Viewport off the Grid Viewport Stack
popViewport | Maintaining and Navigating the Grid Viewport Tree
postDrawDetails | Customising grid Drawing
preDrawDetails | Customising grid Drawing
push.viewport | Push a Viewport onto the Grid Viewport Stack
pushViewport | Maintaining and Navigating the Grid Viewport Tree

-- R --

recordGrob | Encapsulate calculations and drawing
rectGrob | Draw rectangles
removeGrob | Remove a Grid Graphical Object

-- S --

seekViewport | Maintaining and Navigating the Grid Viewport Tree
segmentsGrob | Draw Line Segments
setChildren | Add a Grid Graphical Object
setGrob | Set a Grid Graphical Object
stringHeight | Create a Unit Describing the Width of a String
stringWidth | Create a Unit Describing the Width of a String

-- T --

textGrob Draw Text

-- U --

unit | Function to Create a Unit Object
unit.c | Combine Unit Objects
unit.length | Length of a Unit Object
unit.pmax | Parallel Unit Minima and Maxima
unit.pmin | Parallel Unit Minima and Maxima
unit.rep | Replicate Elements of Unit Objects
upViewport | Maintaining and Navigating the Grid Viewport Tree

-- V --

validDetails | Customising grid grob Validation
viewport | Create a Grid Viewport
vpList | Create a Grid Viewport
vpPath | Concatenate Viewport Names
vpStack | Create a Grid Viewport
vpTree | Create a Grid Viewport

-- W --

widthDetails Width and Height of a grid grob

-- X --

xaxisGrob | Draw an X-Axis
xDetails | Boundary of a grid grob
xsplineGrob | Draw an Xspline

-- Y --

yaxisGrob | Draw a Y-Axis
yDetails | Boundary of a grid grob


Absolute Size of a Grob

Description

This function converts a unit object into absolute units. Absolute units are unaffected, but non-absolute units are converted into "null" units.

Usage

absolute.size(unit)

Arguments

unit An object of class "unit".

Details

Absolute units are things like "inches", "cm", and "lines". Non-absolute units are "npc" and "native".

This function is designed to be used in widthDetails and heightDetails methods.

Value

An object of class "unit".

Author(s)

Paul Murrell

See Also

widthDetails and heightDetails methods.

[Package grid version 2.4.1 Index]


Describe arrows to add to a line.

Description

Produces a description of what arrows to add to a line. The result can be passed to a function that draws a line, e.g., grid.lines.

Usage

arrow(angle = 30, length = unit(0.25, "inches"),
      ends = "last", type = "open")

Arguments

angle | The angle of the arrow head in degrees (smaller numbers produce narrower, pointier arrows). Essentially describes the width of the arrow head.
length | A unit specifying the length of the arrow head (from tip to base).
ends | One of "last", "first", or "both", indicating which ends of the line to draw arrow heads.
type | One of "open" or "closed" indicating whether the arrow head should be a closed triangle.

Examples

arrow()


Convert a Unit Object to Native units

Description

This function is deprecated in grid version 0.8 and will be made defunct in grid version 1.9

You should use the convertUnit() function or one of its close allies instead.

This function returns a numeric vector containing the specified x or y locations or dimensions, converted to "user" or "data" units, relative to the current viewport.

Usage

convertNative(unit, dimension="x", type="location")

Arguments

unit | A unit object.
dimension | Either "x" or "y".
type | Either "location" or "dimension".

Value

A numeric vector.

WARNING

If you draw objects based on output from these conversion functions, then resize your device, the objects will be drawn incorrectly – the base R display list will not recalculate these conversions. This means that you can only rely on the results of these calculations if the size of your device is fixed.

Author(s)

Paul Murrell

See Also

grid.convert, unit

Examples

grid.newpage()
pushViewport(viewport(width=unit(.5, "npc"),
                       height=unit(.5, "npc")))
grid.rect()
w <- convertNative(unit(1, "inches"))
h <- convertNative(unit(1, "inches"), "y")
# This rectangle starts off life as 1in square, but if you
# resize the device it will no longer be 1in square
grid.rect(width=unit(w, "native"), height=unit(h, "native"),
          gp=gpar(col="red"))
popViewport(1)

# How to use grid.convert(), etc instead
convertNative(unit(1, "inches")) ==
  convertX(unit(1, "inches"), "native", valueOnly=TRUE)
convertNative(unit(1, "inches"), "y", "dimension") ==
  convertHeight(unit(1, "inches"), "native", valueOnly=TRUE)


Get the Current Grid Viewport (Tree)

Description

current.viewport() returns the viewport that Grid is going to draw into.

current.vpTree returns the entire Grid viewport tree.

current.vpPath returns the viewport path to the current viewport.

current.transform returns the transformation matrix for the current viewport.

Usage

current.viewport(vp=NULL)
current.vpTree(all=TRUE)
current.vpPath()
current.transform()

Arguments

vp | A Grid viewport object. Use of this argument has been deprecated.
all | A logical value indicating whether the entire viewport tree should be returned.

Details

If all is FALSE then current.vpTree only returns the subtree below the current viewport.

Value

A Grid viewport object from current.viewport or current.vpTree.
current.transform returns a 4x4 transformation matrix.
The viewport path returned by current.vpPath is NULL if the current viewport is the ROOT viewport

Author(s)

Paul Murrell

See Also

viewport

Examples

grid.newpage()
pushViewport(viewport(width=0.8, height=0.8, name="A"))
pushViewport(viewport(x=0.1, width=0.3, height=0.6,
  just="left", name="B"))
upViewport(1)
pushViewport(viewport(x=0.5, width=0.4, height=0.8,
  just="left", name="C"))
pushViewport(viewport(width=0.8, height=0.8, name="D"))
current.vpPath()
upViewport(1)
current.vpPath()
current.vpTree()
current.viewport()
current.vpTree(all=FALSE)
popViewport(0)


Create a Viewport with Scales based on Data

Description

This is a convenience function for producing a viewport with x- and/or y-scales based on numeric values passed to the function.

Usage

dataViewport(xData = NULL, yData = NULL, xscale = NULL,
             yscale = NULL, extension = 0.05, ...)

Arguments

xData | A numeric vector of data.
yData | A numeric vector of data.
xscale | A numeric vector (length 2).
yscale | A numeric vector (length 2).
extension | A numeric. If length greater than 1, then first value is used to extend the xscale and second value is used to extend the yscale.
... | All other arguments will be passed to a call to the viewport() function.

Details

If xscale is not specified then the values in x are used to generate an x-scale based on the range of x, extended by the proportion specified in extension. Similarly for the y-scale.

Value

A grid viewport object.

Author(s)

Paul Murrell

See Also

viewport and plotViewport.


Customising grid Drawing

Description

These generic hook functions are called whenever a grid grob is drawn. They provide an opportunity for customising the drawing of a new class derived from grob (or gTree).

Usage

drawDetails(x, recording)
draw.details(x, recording)
preDrawDetails(x)
postDrawDetails(x)

Arguments

x | A grid grob.
recording | A logical value indicating whether a grob is being added to the display list or redrawn from the display list.

Details

These functions are called by the grid.draw methods for grobs and gTrees.

preDrawDetails is called first during the drawing of a grob. This is where any additional viewports should be pushed (see, for example, grid:::preDrawDetails.frame). Note that the default behaviour for grobs is to push any viewports in the vp slot, and for gTrees is to also push and up any viewports in the childrenvp slot so there is typically nothing to do here.

drawDetails is called next and is where any additional calculations and graphical output should occur (see, for example, grid:::drawDetails.xaxis. Note that the default behaviour for gTrees is to draw all grobs in the children slot so there is typically nothing to do here.

postDrawDetails is called last and should reverse anything done in preDrawDetails (i.e., pop or up any viewports that were pushed; again, see, for example, grid:::postDrawDetails.frame). Note that the default behaviour for grobs is to pop any viewports that were pushed so there is typically nothing to do here.

Note that preDrawDetails and postDrawDetails are also called in the calculation of "grobwidth" and "grobheight" units.

Value

None of these functions are expected to return a value.

Author(s)

Paul Murrell

See Also

grid.draw


Customising grid Editing

Description

This generic hook function is called whenever a grid grob is edited via grid.edit or editGrob. This provides an opportunity for customising the editing of a new class derived from grob (or gTree).

Usage

editDetails(x, specs)

Arguments

x | A grid grob.
specs | A list of named elements. The names indicate the grob slots to modify and the values are the new values for the slots.

Details

This function is called by grid.edit and editGrob. A method should be written for classes derived from grob or gTree if a change in a slot has an effect on other slots in the grob or children of a gTree (e.g., see grid:::editDetails.xaxis).

Note that the slot already has the new value.

Value

The function MUST return the modified grob.

Author(s)

Paul Murrell

See Also

grid.edit


Create and Apply Edit Objects

Description

The functions gEdit and gEditList create objects representing an edit operation (essentially a list of arguments to editGrob).

The functions applyEdit and applyEdits apply one or more edit operations to a graphical object.

These functions are most useful for developers creating new graphical functions and objects.

Usage

gEdit(...)
gEditList(...)
applyEdit(x, edit)
applyEdits(x, edits)

Arguments

... | one or more arguments to the editGrob function (for gEdit) or one or more "gEdit" objects (for gEditList).
x | a grob (grid graphical object).
edit | a "gEdit" object.
edits | either a "gEdit" object or a "gEditList" object.

Value

gEdit returns an object of class "gEdit".
gEditList returns an object of class "gEditList".
applyEdit and applyEditList return the modified grob.

Author(s)

Paul Murrell

See Also

grob editGrob

Examples

grid.rect(gp=gpar(col="red"))
# same thing, but more verbose
grid.draw(applyEdit(rectGrob(), gEdit(gp=gpar(col="red"))))


List the names of grobs on the display list

Description

Returns a character vector containing the names of all top-level grobs on the display list.

Usage

getNames()

Value

A character vector.

Author(s)

Paul Murrell

Examples

grid.grill()
getNames()


Handling Grid Graphical Parameters

Description

gpar() should be used to create a set of graphical parameter settings. It returns an object of class "gpar". This is basically a list of name-value pairs.

get.gpar() can be used to query the current graphical parameter settings.

Usage

gpar(...)
get.gpar(names = NULL)

Arguments

... | Any number of named arguments.
names | A character vector of valid graphical parameter names.

Details

All grid viewports and (predefined) graphical objects have a slot called gp, which contains a "gpar" object. When a viewport is pushed onto the viewport stack and when a graphical object is drawn, the settings in the "gpar" object are enforced. In this way, the graphical output is modified by the gp settings until the graphical object has finished drawing, or until the viewport is popped off the viewport stack, or until some other viewport or graphical object is pushed or begins drawing.

Valid parameter names are:
col | Colour for lines and borders.
fill | Colour for filling rectangles, polygons, ...
alpha | Alpha channel for transparency
lty | Line type
lwd | Line width
lex | Multiplier applied to line width
lineend | Line end style (round, butt, square)
linejoin | Line join style (round, mitre, bevel)
linemitre | Line mitre limit (number greater than 1)
fontsize | The size of text (in points)
cex | Multiplier applied to fontsize
fontfamily | The font family
fontface | The font face (bold, italic, ...)
lineheight | The height of a line as a multiple of the size of text
font | Font face (alias for fontface; for backward compatibility)

The alpha setting is combined with the alpha channel for individual colours by multiplying (with both alpha settings normalised to the range 0 to 1).

The size of text is fontsize*cex. The size of a line is fontsize*cex*lineheight.

The cex setting is cumulative; if a viewport is pushed with a cex of 0.5 then another viewport is pushed with a cex of 0.5, the effective cex is 0.25.

The alpha and lex settings are also cumulative.

Changes to the fontfamily may be ignored by some devices, but is supported by PostScript, PDF, X11, Windows, and Quartz. The fontfamily may be used to specify one of the Hershey Font families (e.g., HersheySerif) and this specification will be honoured on all devices.

The specification of fontface can be an integer or a string. If an integer, then it follows the R base graphics standard: 1 = plain, 2 = bold, 3 = italic, 4 = bold italic. If a string, then valid values are: "plain", "bold", "italic", "oblique", and "bold.italic". For the special case of the HersheySerif font family, "cyrillic", "cyrillic.oblique", and "EUC" are also available.

Specifying the value NULL for a parameter is the same as not specifying any value for that parameter, except for col and fill, where NULL indicates not to draw a border or not to fill an area (respectively).

All parameter values can be vectors of multiple values. (This will not always make sense – for example, viewports will only take notice of the first parameter value.)

The gamma parameter is deprecated.

get.gpar() returns all current graphical parameter settings.

Value

An object of class "gpar".

Author(s)

Paul Murrell

See Also

Hershey.

Examples

gp <- get.gpar()
utils::str(gp)
## These *do* nothing but produce a "gpar" object:
gpar(col = "red")
gpar(col = "blue", lty = "solid", lwd = 3, fontsize = 16)
get.gpar(c("col", "lty"))
grid.newpage()
vp <- viewport(w = .8, h = .8, gp = gpar(col="blue"))
grid.draw(gTree(children=gList(rectGrob(gp = gpar(col="red")),
                     textGrob(paste("The rect is its own colour (red)",
                                    "but this text is the colour",
                                    "set by the gTree (green)",
                                    sep = "\n"))),
      gp = gpar(col="green"), vp = vp))
grid.text("This text is the colour set by the viewport (blue)",
          y = 1, just = c("center", "bottom"),
          gp = gpar(fontsize=20), vp = vp)
grid.newpage()
## example with multiple values for a parameter
pushViewport(viewport())
grid.points(1:10/11, 1:10/11, gp = gpar(col=1:10))
popViewport()


Concatenate Grob Names

Description

This function can be used to generate a grob path for use in grid.edit and friends.

A grob path is a list of nested grob names.

Usage

gPath(...)

Arguments

... Character values which are grob names.

Details

Grob names must only be unique amongst grobs which share the same parent in a gTree.

This function can be used to generate a specification for a grob that includes the grob's parent's name (and the name of its parent and so on).

For interactive use, it is possible to directly specify a path, but it is strongly recommended that this function is used otherwise in case the path separator is changed in future versions of grid.

Value

A gPath object.

See Also

grob, editGrob, addGrob, removeGrob, getGrob, setGrob

Examples

gPath("g1", "g2")


Grid Graphics

Description

General information about the grid graphics package.

Details

Grid graphics provides an alternative to the standard R graphics. The user is able to define arbitrary rectangular regions (called viewports) on the graphics device and define a number of coordinate systems for each region. Drawing can be specified to occur in any viewport using any of the available coordinate systems.

Grid graphics and standard R graphics do not mix!

Type library(help = grid) to see a list of (public) Grid graphics functions.

Author(s)

Paul Murrell

See Also

viewport, grid.layout, and unit.

Examples

## Diagram of a simple layout
grid.show.layout(grid.layout(4,2,
                     heights=unit(rep(1, 4),
                                  c("lines", "lines", "lines", "null")),
                     widths=unit(c(1, 1), "inches")))
## Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
                            w=unit(1, "inches"), h=unit(1, "inches")))
## A flash plotting example
grid.multipanel(vp=viewport(0.5, 0.5, 0.8, 0.8))


Internal Grid Functions

Description

Internal Grid functions

Details

These are not to be called by the user (or in some cases are just waiting for proper documentation to be written :).


The Grid Graphics Package

Description

A rewrite of the graphics layout capabilities, plus some support for interaction.

Details

This package contains a graphics system which supplements old-style S graphics.

Further information is available in the following vignettes:
displaylist | Display Lists in grid (source, pdf)
frame | Frames and packing grobs (source, pdf)
grid | Introduction to grid (source, pdf)
grobs | Working with grid grobs (source, pdf)
interactive | Editing grid Graphics (source, pdf)
locndimn | Locations versus Dimensions (source, pdf)
moveline | Demonstrating move-to and line-to (source, pdf)
nonfinite | Non-finite values (source, pdf)
plotexample | Writing grid Code (source, pdf)
rotated | Rotated Viewports (source, pdf)
saveload | Persistent representations (source, pdf)
sharing | Modifying multiple grobs simultaneously (source, pdf)
viewports | Working with viewports (source, pdf)

For a complete list of functions with individual help pages, use library(help="grid").

Author(s)

Paul Murrell paul@stat.auckland.ac.nz

Maintainer: R Core Team R-core@r-project.org

References

Murrell, P. (2005) R Graphics. Chapman & Hall/CRC Press.


Add a Grid Graphical Object

Description

Add a grob to a gTree or a descendant of a gTree.

Usage

grid.add(gPath, child, strict = FALSE, grep = FALSE,
         global = FALSE, allDevices = FALSE, redraw = TRUE)

addGrob(gTree, child, gPath = NULL, strict = FALSE, grep = FALSE,
        global = FALSE)

setChildren(x, children)

Arguments

gTree, x | A gTree object.
gPath | A gPath object. For grid.add this specifyies a gTree on the display list. For addGrob this specifies a descendant of the specified gTree.
child | A grob object.
children | A gList object.
strict | A boolean indicating whether the gPath must be matched exactly.
grep | A boolean indicating whether the gPath should be treated as a regular expression. Values are recycled across elements of the gPath (e.g., c(TRUE, FALSE) means that every odd element of the gPath will be treated as a regular expression).
global | A boolean indicating whether the function should affect just the first match of the gPath, or whether all matches should be affected.
allDevices | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED.
redraw | A logical value to indicate whether to redraw the grob.

Details

addGrob copies the specified grob and returns a modified grob.

grid.add destructively modifies a grob on the display list. If redraw is TRUE it then redraws everything to reflect the change.

setChildren is a basic function for setting all children of a gTree at once (instead of repeated calls to addGrob).

Value

addGrob returns a grob object; grid.add returns NULL.

Author(s)

Paul Murrell

See Also

grob, getGrob, addGrob, removeGrob.


Draw Arrows

Description

Functions to create and draw arrows at either end of a line, or at either end of a line.to, lines, or segments grob.

These functions have been deprecated in favour of arrow arguments to the line-related primitives.

Usage

grid.arrows(x = c(0.25, 0.75), y = 0.5, default.units = "npc",
            grob = NULL,
            angle = 30, length = unit(0.25, "inches"),
            ends = "last", type = "open", name = NULL,
            gp = gpar(), draw = TRUE, vp = NULL)

arrowsGrob(x = c(0.25, 0.75), y = 0.5, default.units = "npc",
            grob = NULL,
            angle = 30, length = unit(0.25, "inches"),
            ends = "last", type = "open", name = NULL,
            gp = gpar(), vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-values.
y | A numeric vector or unit object specifying y-values.
default.units | A string indicating the default units to use if x or y are only given as numeric vectors.
grob | A grob to add arrows to; currently can only be a line.to, lines, or segments grob.
angle | A numeric specifying (half) the width of the arrow head (in degrees).
length | A unit object specifying the length of the arrow head.
ends | One of "first", "last", or "both", indicating which end of the line to add arrow heads.
type | Either "open" or "closed" to indicate the type of arrow head.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create an arrows grob (a graphical object describing arrows), but only grid.arrows() draws the arrows (and then only if draw is TRUE).

If the grob argument is specified, this overrides any x and/or y arguments.

Value

An arrows grob. grid.arrows() returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport, grid.line.to, grid.lines, grid.segments

Examples

## Not run:
## to avoid lots of deprecation warnings
pushViewport(viewport(layout=grid.layout(2, 4)))
pushViewport(viewport(layout.pos.col=1,
                       layout.pos.row=1))
grid.rect(gp=gpar(col="grey"))
grid.arrows()
popViewport()
pushViewport(viewport(layout.pos.col=2,
                       layout.pos.row=1))
grid.rect(gp=gpar(col="grey"))
grid.arrows(angle=15, type="closed")
popViewport()
pushViewport(viewport(layout.pos.col=3,
                       layout.pos.row=1))
grid.rect(gp=gpar(col="grey"))
grid.arrows(angle=5, length=unit(0.1, "npc"),
            type="closed", gp=gpar(fill="white"))
popViewport()
pushViewport(viewport(layout.pos.col=4,
                       layout.pos.row=1))
grid.rect(gp=gpar(col="grey"))
grid.arrows(x=unit(0:80/100, "npc"),
            y=unit(1 - (0:80/100)^2, "npc"))
popViewport()
pushViewport(viewport(layout.pos.col=1,
                       layout.pos.row=2))
grid.rect(gp=gpar(col="grey"))
grid.arrows(ends="both")
popViewport()
pushViewport(viewport(layout.pos.col=2,
                       layout.pos.row=2))
grid.rect(gp=gpar(col="grey"))
# Recycling arguments
grid.arrows(x=unit(1:10/11, "npc"), y=unit(1:3/4, "npc"))
popViewport()
pushViewport(viewport(layout.pos.col=3,
                       layout.pos.row=2))
grid.rect(gp=gpar(col="grey"))
# Drawing arrows on a segments grob
gs <- segmentsGrob(x0=unit(1:4/5, "npc"),
                   x1=unit(1:4/5, "npc"))
grid.arrows(grob=gs, length=unit(0.1, "npc"),
            type="closed", gp=gpar(fill="white"))
popViewport()
pushViewport(viewport(layout.pos.col=4,
                       layout.pos.row=2))
grid.rect(gp=gpar(col="grey"))
# Arrows on a lines grob
# Name these because going to grid.edit them later
gl <- linesGrob(name="curve", x=unit(0:80/100, "npc"),
                y=unit((0:80/100)^2, "npc"))
grid.arrows(name="arrowOnLine", grob=gl, angle=15, type="closed",
            gp=gpar(fill="black"))
popViewport()
pushViewport(viewport(layout.pos.col=1,
                       layout.pos.row=2))
grid.move.to(x=0.5, y=0.8)
popViewport()
pushViewport(viewport(layout.pos.col=4,
                       layout.pos.row=1))
# Arrows on a line.to grob
glt <- lineToGrob(x=0.5, y=0.2, gp=gpar(lwd=3))
grid.arrows(grob=glt, ends="first", gp=gpar(lwd=3))
popViewport(2)
grid.edit(gPath("arrowOnLine", "curve"), y=unit((0:80/100)^3, "npc"))
## End(Not run)


Draw a Circle

Description

Functions to create and draw a circle.

Usage

grid.circle(x=0.5, y=0.5, r=0.5, default.units="npc", name=NULL,
            gp=gpar(), draw=TRUE, vp=NULL)
circleGrob(x=0.5, y=0.5, r=0.5, default.units="npc", name=NULL,
            gp=gpar(), vp=NULL)

Arguments

x | A numeric vector or unit object specifying x-locations.
y | A numeric vector or unit object specifying y-locations.
r | A numeric vector or unit object specifying radii.
default.units | A string indicating the default units to use if x, y, width, or height are only given as numeric vectors.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create a circle grob (a graphical object describing a circle), but only grid.circle() draws the circle (and then only if draw is TRUE).

The radius may be given in any units; if the units are relative (e.g., "npc" or "native") then the radius will be different depending on whether it is interpreted as a width or as a height. In such cases, the smaller of these two values will be the result. To see the effect, type grid.circle() and adjust the size of the window.

Value

A circle grob. grid.circle() returns the value invisibly.

Warning

Negative values for the radius are silently converted to their absolute value.

Author(s)

Paul Murrell

See Also

Grid, viewport


Set the Clipping Region

Description

These functions set the clipping region within the current viewport without altering the current coordinate system.

Usage

grid.clip(...)
clipGrob(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
         width = unit(1, "npc"), height = unit(1, "npc"),
         just = "centre", hjust = NULL, vjust = NULL,
         default.units = "npc", name = NULL, vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-location.
y | A numeric vector or unit object specifying y-location.
width | A numeric vector or unit object specifying width.
height | A numeric vector or unit object specifying height.
just | The justification of the clip rectangle relative to its (x, y) location. If there are two values, the first value specifes horizontal justification and the second value specifies vertical justification. Possible string values are: "left", "right", "centre", "center", "bottom", and "top". For numeric values, 0 means left alignment and 1 means right alignment.
hjust | A numeric vector specifying horizontal justification. If specified, overrides the just setting.
vjust | A numeric vector specifying vertical justification. If specified, overrides the just setting.
default.units | A string indicating the default units to use if x, y, width, or height are only given as numeric vectors.
name | A character identifier.
vp | A Grid viewport object (or NULL).
... | Arguments passed to clipGrob.

Details

Both functions create a clip rectangle (a graphical object describing a clip rectangle), but only grid.clip enforces the clipping.

Pushing or popping a viewport always overrides the clip region set by a clip grob, regardless of whether that viewport explicitly enforces a clipping region.

Value

clipGrob returns a clip grob.

Author(s)

Paul Murrell

See Also

Grid, viewport

Examples

# draw across entire viewport, but clipped
grid.clip(x = 0.3, width = 0.1)
grid.lines(gp=gpar(col="green", lwd=5))
# draw across entire viewport, but clipped (in different place)
grid.clip(x = 0.7, width = 0.1)
grid.lines(gp=gpar(col="red", lwd=5))
# Viewport sets new clip region
pushViewport(viewport(width=0.5, height=0.5, clip=TRUE))
grid.lines(gp=gpar(col="grey", lwd=3))
# Return to original viewport;  get
# clip region from previous grid.clip()
# (NOT from previous viewport clip region)
popViewport()
grid.lines(gp=gpar(col="black"))


Create a Coherent Group of Grid Graphical Objects

Description

This function is deprecated; please use gTree.

This function creates a graphical object which contains several other graphical objects. When it is drawn, it draws all of its children.

It may be convenient to name the elements of the collection.

Usage

grid.collection(..., gp=gpar(), draw=TRUE, vp=NULL)

Arguments

... | Zero or more objects of class "grob".
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value to indicate whether to produce graphical output.
vp | A Grid viewport object (or NULL).

Value

A collection grob.

Author(s)

Paul Murrell

See Also

grid.grob.


Convert Between Different grid Coordinate Systems

Description

These functions take a unit object and convert it to an equivalent unit object in a different coordinate system.

Usage

convertX(x, unitTo, valueOnly = FALSE)
convertY(x, unitTo, valueOnly = FALSE)
convertWidth(x, unitTo, valueOnly = FALSE)
convertHeight(x, unitTo, valueOnly = FALSE)
convertUnit(x, unitTo,
             axisFrom = "x", typeFrom = "location",
             axisTo = axisFrom, typeTo = typeFrom,
             valueOnly = FALSE)
grid.convertX(x, unitTo, valueOnly = FALSE)
grid.convertY(x, unitTo, valueOnly = FALSE)
grid.convertWidth(x, unitTo, valueOnly = FALSE)
grid.convertHeight(x, unitTo, valueOnly = FALSE)
grid.convert(x, unitTo,
             axisFrom = "x", typeFrom = "location",
             axisTo = axisFrom, typeTo = typeFrom,
             valueOnly = FALSE)

Arguments

x | A unit object.
unitTo | The coordinate system to convert the unit to. See the unit function for valid coordinate systems.
axisFrom | Either "x" or "y" to indicate whether the unit object represents a value in the x- or y-direction.
typeFrom | Either "location" or "dimension" to indicate whether the unit object represents a location or a length.
axisTo | Same as axisFrom, but applies to the unit object that is to be created.
typeTo | Same as typeFrom, but applies to the unit object that is to be created.
valueOnly | A logical indicating. If TRUE then the function does not return a unit object, but rather only the converted numeric values.

Details

The convertUnit function allows for general-purpose conversions. The other four functions are just more convenient front-ends to it for the most common conversions.

The conversions occur within the current viewport.

It is not currently possible to convert to all valid coordinate systems (e.g., "strwidth" or "grobwidth"). I'm not sure if all of these are impossible, they just seem implausible at this stage.

In normal usage of grid, these functions should not be necessary. If you want to express a location or dimension in inches rather than user coordinates then you should simply do something like unit(1, "inches") rather than something like unit(0.134, "native").

In some cases, however, it is necessary for the user to perform calculations on a unit value and this function becomes necessary. In such cases, please take note of the warning below.

The grid.* versions are just previous incarnations which have been deprecated.

Value

A unit object in the specified coordinate system (unless valueOnly is TRUE in which case the returned value is a numeric).

Warning

The conversion is only valid for the current device size. If the device is resized then at least some conversions will become invalid. For example, suppose that I create a unit object as follows: oneinch <- convertUnit(unit(1, "inches"), "native". Now if I resize the device, the unit object in oneinch no longer corresponds to a physical length of 1 inch.

Author(s)

Paul Murrell

See Also

unit

Examples

## A tautology
convertX(unit(1, "inches"), "inches")
## The physical units
convertX(unit(2.54, "cm"), "inches")
convertX(unit(25.4, "mm"), "inches")
convertX(unit(72.27, "points"), "inches")
convertX(unit(1/12*72.27, "picas"), "inches")
convertX(unit(72, "bigpts"), "inches")
convertX(unit(1157/1238*72.27, "dida"), "inches")
convertX(unit(1/12*1157/1238*72.27, "cicero"), "inches")
convertX(unit(65536*72.27, "scaledpts"), "inches")
convertX(unit(1/2.54, "inches"), "cm")
convertX(unit(1/25.4, "inches"), "mm")
convertX(unit(1/72.27, "inches"), "points")
convertX(unit(1/(1/12*72.27), "inches"), "picas")
convertX(unit(1/72, "inches"), "bigpts")
convertX(unit(1/(1157/1238*72.27), "inches"), "dida")
convertX(unit(1/(1/12*1157/1238*72.27), "inches"), "cicero")
convertX(unit(1/(65536*72.27), "inches"), "scaledpts")

pushViewport(viewport(width=unit(1, "inches"),
                       height=unit(2, "inches"),
                       xscale=c(0, 1),
                       yscale=c(1, 3)))
  ## Location versus dimension
  convertY(unit(2, "native"), "inches")
  convertHeight(unit(2, "native"), "inches")
  ## From "x" to "y" (the conversion is via "inches")
  convertUnit(unit(1, "native"), "native",
               axisFrom="x", axisTo="y")
  ## Convert several values at once
  convertX(unit(c(0.5, 2.54), c("npc", "cm")),
                c("inches", "native"))
popViewport()
## Convert a complex unit
convertX(unit(1, "strwidth", "Hello"), "native")


Make a Copy of a Grid Graphical Object

Description

This function is redundant and will disappear in future versions.

Usage

grid.copy(grob)

Arguments

grob A grob object.

Value

A copy of the grob object.

Author(s)

Paul Murrell

See Also

grid.grob.


Draw a Curve Between Locations

Description

These functions create and draw a curve from one location to another.

Usage

grid.curve(...)
curveGrob(x1, y1, x2, y2, default.units = "npc",
          curvature = 1, angle = 90, ncp = 1, shape = 0.5,
          square = TRUE, squareShape = 1,
          inflect = FALSE, arrow = NULL, debug = FALSE,
          name = NULL, gp = gpar(), vp = NULL)
arcCurvature(theta)

Arguments

x1 | A numeric vector or unit object specifying the x-location of the start point.
y1 | A numeric vector or unit object specifying the y-location of the start point.
x2 | A numeric vector or unit object specifying the x-location of the end point.
y2 | A numeric vector or unit object specifying the y-location of the end point.
default.units | A string indicating the default units to use if x1, y1, x2 or y2 are only given as numeric values.
curvature | A numeric value giving the amount of curvature. Negative values produce left-hand curves, positive values produce right-hand curves, and zero produces a straight line.
angle | A numeric value between 0 and 180, giving an amount to skew the control points of the curve. Values less than 90 skew the curve towards the start point and values greater than 90 skew the curve towards the end point.
ncp | The number of control points used to draw the curve. More control points creates a smoother curve.
shape | A numeric vector of values between -1 and 1, which control the shape of the curve relative to its control points. See grid.xspline for more details.
square | A logical value that controls whether control points for the curve are created city-block fashion or obliquely. When ncp is 1 and angle is 90, this is typically TRUE, otherwise this should probably be set to FALSE (see Examples below).
squareShape | A shape value to control the behaviour of the curve relative to any additional control point that is inserted if square is TRUE.
inflect | A logical value specifying whether the curve should be cut in half and inverted (see Examples below).
arrow | A list describing arrow heads to place at either end of the curve, as produced by the arrow function.
debug | A logical value indicating whether debugging information should be drawn.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A Grid viewport object (or NULL).
... | Arguments to be passed to curveGrob.
theta | An angle (in degrees).

Details

Both functions create a curve grob (a graphical object describing an curve), but only grid.curve draws the curve.

The arcCurvature function can be used to calculate a curvature such that control points are generated on an arc corresponding to angle theta. This is typically used in conjunction with a large ncp to produce a curve corresponding to the desired arc.

Value

A grob object.

See Also

Grid, viewport, grid.xspline, arrow

Examples

curveTest <- function(i, j, ...) {
  pushViewport(viewport(layout.pos.col=j, layout.pos.row=i))
  do.call("grid.curve", c(list(x1=.25, y1=.25, x2=.75, y2=.75),
          if (is.null(...)) NULL else list(...)))
  grid.text(sub("list", "", deparse(substitute(list(...)))),
            y=unit(1, "npc"))
  popViewport()
}
# grid.newpage()
pushViewport(plotViewport(c(0, 0, 1, 0),
                          layout=grid.layout(2, 1, heights=c(2, 1))))
pushViewport(viewport(layout.pos.row=1,
                      layout=grid.layout(3, 3, respect=TRUE)))
curveTest(1, 1, NULL)
curveTest(1, 2, inflect=TRUE)
curveTest(1, 3, angle=135)
curveTest(2, 1, arrow=arrow())
curveTest(2, 2, ncp=8)
curveTest(2, 3, shape=0)
curveTest(3, 1, curvature=-1)
curveTest(3, 2, square=FALSE)
curveTest(3, 3, debug=TRUE)
popViewport()
pushViewport(viewport(layout.pos.row=2,
                      layout=grid.layout(3, 3)))
curveTest(1, 1, NULL)
curveTest(1, 2, inflect=TRUE)
curveTest(1, 3, angle=135)
curveTest(2, 1, arrow=arrow())
curveTest(2, 2, ncp=8)
curveTest(2, 3, shape=0)
curveTest(3, 1, curvature=-1)
curveTest(3, 2, square=FALSE)
curveTest(3, 3, debug=TRUE)
popViewport(2)


Control the Grid Display List

Description

Turn the Grid display list on or off.

Usage

grid.display.list(on=TRUE)
engine.display.list(on=TRUE)

Arguments

on A logical value to indicate whether the display list should be on or off.

Details

All drawing and viewport-setting operations are (by default) recorded in the Grid display list. This allows redrawing to occur following an editing operation.

This display list could get very large so it may be useful to turn it off in some cases; this will of course disable redrawing.

All graphics output is also recorded on the main display list of the R graphics engine (by default). This supports redrawing following a device resize and allows copying between devices.

Turning off this display list means that grid will redraw from its own display list for device resizes and copies. This will be slower than using the graphics engine display list.

Value

None.

WARNING

Turning the display list on causes the display list to be erased!

Turning off both the grid display list and the graphics engine display list will result in no redrawing whatsoever.

Author(s)

Paul Murrell


Draw a grid grob

Description

Produces graphical output from a graphical object.

Usage

grid.draw(x, recording=TRUE)

Arguments

x | An object of class "grob" or NULL.
recording | A logical value to indicate whether the drawing operation should be recorded on the Grid display list.

Details

This is a generic function with methods for grob and gTree objects.

The grob and gTree methods automatically push any viewports in a vp slot and automatically apply any gpar settings in a gp slot. In addition, the gTree method pushes and ups any viewports in a childrenvp slot and automatically calls grid.draw for any grobs in a children slot.

The methods for grob and gTree call the generic hook functions preDrawDetails, drawDetails, and postDrawDetails to allow classes derived from grob or gTree to perform additional viewport pushing/popping and produce additional output beyond the default behaviour for grobs and gTrees.

Value

None.

Author(s)

Paul Murrell

See Also

grob.

Examples

grid.newpage()
## Create a graphical object, but don't draw it
l <- linesGrob()
## Draw it
grid.draw(l)


Edit the Description of a Grid Graphical Object

Description

Changes the value of one of the slots of a grob and redraws the grob.

Usage

grid.edit(gPath, ..., strict = FALSE, grep = FALSE, global = FALSE,
          allDevices = FALSE, redraw = TRUE)
editGrob(grob, gPath = NULL, ..., strict = FALSE, grep = FALSE,
         global = FALSE)

Arguments

grob | A grob object.
... | Zero or more named arguments specifying new slot values.
gPath | A gPath object. For grid.edit this specifyies a grob on the display list. For editGrob this specifies a descendant of the specified grob.
strict | A boolean indicating whether the gPath must be matched exactly.
grep | A boolean indicating whether the gPath should be treated as a regular expression. Values are recycled across elements of the gPath (e.g., c(TRUE, FALSE) means that every odd element of the gPath will be treated as a regular expression).
global | A boolean indicating whether the function should affect just the first match of the gPath, or whether all matches should be affected.
allDevices | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED.
redraw | A logical value to indicate whether to redraw the grob.

Details

editGrob copies the specified grob and returns a modified grob.

grid.edit destructively modifies a grob on the display list. If redraw is TRUE it then redraws everything to reflect the change.

Both functions call editDetails to allow a grob to perform custom actions and validDetails to check that the modified grob is still coherent.

Value

editGrob returns a grob object; grid.edit returns NULL.

Author(s)

Paul Murrell

See Also

grob, getGrob, addGrob, removeGrob.

Examples

grid.newpage()
grid.xaxis(name = "xa", vp = viewport(width=.5, height=.5))
grid.edit("xa", gp = gpar(col="red"))
# won't work because no ticks (at is NULL)
try(grid.edit(gPath("xa", "ticks"), gp = gpar(col="green")))
grid.edit("xa", at = 1:4/5)
# Now it should work
try(grid.edit(gPath("xa", "ticks"), gp = gpar(col="green")))


Create a Frame for Packing Objects

Description

These functions, together with grid.pack, grid.place, packGrob, and placeGrob are part of a GUI-builder-like interface to constructing graphical images. The idea is that you create a frame with this function then use grid.pack or whatever to pack/place objects into the frame.

Usage

grid.frame(layout=NULL, name=NULL, gp=gpar(), vp=NULL, draw=TRUE)
frameGrob(layout=NULL, name=NULL, gp=gpar(), vp=NULL)

Arguments

layout | A Grid layout, or NULL. This can be used to initialise the frame with a number of rows and columns, with initial widths and heights, etc.
name | A character identifier.
vp | An object of class viewport, or NULL.
gp | An object of class gpar; typically the output from a call to the function gpar.
draw | Should the frame be drawn.

Details

Both functions create a frame grob (a graphical object describing a frame), but only grid.frame() draws the frame (and then only if draw is TRUE). Nothing will actually be drawn, but it will put the frame on the display list, which means that the output will be dynamically updated as objects are packed into the frame. Possibly useful for debugging.

Value

A frame grob. grid.frame() returns the value invisibly.

Author(s)

Paul Murrell

See Also

grid.pack

Examples

grid.newpage()
grid.frame(name="gf", draw=TRUE)
grid.pack("gf", rectGrob(gp=gpar(fill="grey")), width=unit(1, "null"))
grid.pack("gf", textGrob("hi there"), side="right")


Get a Grid Graphical Object

Description

Retrieve a grob or a descendant of a grob.

Usage

grid.get(gPath, strict = FALSE, grep = FALSE, global = FALSE,
         allDevices = FALSE)

getGrob(gTree, gPath, strict = FALSE, grep = FALSE, global = FALSE)

Arguments

gTree | A gTree object.
gPath | A gPath object. For grid.get this specifyies a grob on the display list. For getGrob this specifies a descendant of the specified gTree.
strict | A boolean indicating whether the gPath must be matched exactly.
grep | A boolean indicating whether the gPath should be treated as a regular expression. Values are recycled across elements of the gPath (e.g., c(TRUE, FALSE) means that every odd element of the gPath will be treated as a regular expression).
global | A boolean indicating whether the function should affect just the first match of the gPath, or whether all matches should be affected.
allDevices | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED.

Value

A grob object.

Author(s)

Paul Murrell

See Also

grob, getGrob, addGrob, removeGrob.

Examples

grid.xaxis(name="xa")
grid.get("xa")
grid.get(gPath("xa", "ticks"))

grid.draw(gTree(name="gt", children=gList(xaxisGrob(name="axis"))))
grid.get(gPath("gt", "axis", "ticks"))


Grab the current grid output

Description

Creates a gTree object from the current grid display list or from a scene generated by user-specified code.

Usage

grid.grab(warn = 2, wrap = FALSE, ...)
grid.grabExpr(expr, warn = 2, wrap = FALSE, ...)

Arguments

expr | An expression to be evaluated. Typically, some calls to grid drawing functions.
warn | An integer specifying the amount of warnings to emit. 0 means no warnings, 1 means warn when it is certain that the grab will not faithfully represent the original scene. 2 means warn if there's any possibility that the grab will not faithfully represent the original scene.
wrap | A logical indicating how the output should be captured. If TRUE, each non-grob element on the display list is captured by wrapping it in a grob.
... | arguments passed to gTree, for example, a name and/or class for the gTree that is created.

Details

There are four ways to capture grid output as a gTree.

There are two functions for capturing output: use grid.grab to capture an existing drawing and grid.grabExpr to capture the output from an expression (without drawing anything).

For each of these functions, the output can be captured in two ways. One way tries to be clever and make a gTree with a childrenvp slot containing all viewports on the display list (including those that are popped) and every grob on the display list as a child of the new gTree; each child has a vpPath in the vp slot so that it is drawn in the appropriate viewport. In other words, the gTree contains all elements on the display list, but in a slightly altered form.

The other way, wrap=TRUE, is to create a grob for every element on the display list (and make all of those grobs children of the gTree).

The first approach creates a more compact and elegant gTree, which is more flexible to work with, but is not guaranteed to faithfully replicate all possible grid output. The second approach is more brute force, and harder to work with, but should always faithfully replicate the original output.

Value

A gTree object.

See Also

gTree

Examples

pushViewport(viewport(w=.5, h=.5))
grid.rect()
grid.points(runif(10), runif(10))
popViewport()
grab <- grid.grab()
grid.newpage()
grid.draw(grab)


Draw a Grill

Description

This function draws a grill within a Grid viewport.

Usage

grid.grill(h = unit(seq(0.25, 0.75, 0.25), "npc"),
           v = unit(seq(0.25, 0.75, 0.25), "npc"),
           default.units = "npc", gp=gpar(col = "grey"), vp = NULL)

Arguments

h | A numeric vector or unit object indicating the horizontal location of the vertical grill lines.
v | A numeric vector or unit object indicating the vertical location of the horizontal grill lines.
default.units | A string indicating the default units to use if h or v are only given as numeric vectors.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A Grid viewport object.

Value

None.

Author(s)

Paul Murrell

See Also

Grid, viewport.


Create a Grid Graphical Object

Description

These functions create grid graphical objects.

Usage

grid.grob(list.struct, cl = NULL, draw = TRUE)
grob(..., name = NULL, gp = NULL, vp = NULL, cl = NULL)
gTree(..., name = NULL, gp = NULL, vp = NULL, children = NULL,
      childrenvp = NULL, cl = NULL)
childNames(gTree)
gList(...)

Arguments

... | For grob and gTree, the named slots describing important features of the graphical object. For gList, a series of grob objects.
list.struct | A list (preferably with each element named).
name | A character identifier for the grob. Used to find the grob on the display list and/or as a child of another grob.
children | A gList object.
childrenvp | A viewport object (or NULL).
gp | A gpar object, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A viewport object (or NULL).
cl | A string giving the class attribute for the list.struct
draw | A logical value to indicate whether to produce graphical output.
gTree | A gTree object.

Details

These functions can be used to create a basic grob, gTree, or gList object, or a new class derived from one of these.

A grid graphical object (grob) is a description of a graphical item. These basic classes provide default behaviour for validating, drawing, and modifying graphical objects. Both call the function validDetails to check that the object returned is coherent.

A gTree can have other grobs as children; when a gTree is drawn, it draws all of its children. Before drawing its children, a gTree pushes its childrenvp slot and then navigates back up (calls upViewport) so that the children can specify their location within the childrenvp via a vpPath.

Grob names need not be unique in general, but all children of a gTree must have different names. A grob name can be any string, though it is not advisable to use the gPath separator (currently ::) in grob names.

The function childNames returns the names of the grobs which are children of a gTree.

All grid primitives (grid.lines, grid.rect, ...) and some higher-level grid components (e.g., grid.xaxis and grid.yaxis) are derived from these classes.

grid.grob is deprecated.

Value

A grob object.

Author(s)

Paul Murrell

See Also

grid.draw, grid.edit, grid.get.

Examples

[Package grid version 2.4.1 Index]


Create a Grid Layout

Description

This function returns a Grid layout, which describes a subdivision of a rectangular region.

Usage

grid.layout(nrow = 1, ncol = 1,
        widths = unit(rep(1, ncol), "null"),
        heights = unit(rep(1, nrow), "null"),
        default.units = "null", respect = FALSE,
        just="centre")

Arguments

nrow | An integer describing the number of rows in the layout.
ncol | An integer describing the number of columns in the layout.
widths | A numeric vector or unit object describing the widths of the columns in the layout.
heights | A numeric vector or unit object describing the heights of the rows in the layout.
default.units | A string indicating the default units to use if widths or heights are only given as numeric vectors.
respect | A logical value or a numeric matrix. If a logical, this indicates whether row heights and column widths should respect each other. If a matrix, non-zero values indicate that the corresponding row and column should be respected (see examples below).
just | A string vector indicating how the layout should be justified if it is not the same size as its parent viewport. If there are two values, the first value specifes horizontal justification and the second value specifies vertical justification. Possible values are: "left", "right", "centre", "center", "bottom", and "top". NOTE that in this context, "left", for example, means align the left edge of the left-most layout column with the left edge of the parent viewport.

Details

The unit objects given for the widths and heights of a layout may use a special units that only has meaning for layouts. This is the "null" unit, which indicates what relative fraction of the available width/height the column/row occupies. See the reference for a better description of relative widths and heights in layouts.

Value

A Grid layout object.

WARNING

This function must NOT be confused with the base R graphics function layout. In particular, do not use layout in combination with Grid graphics. The documentation for layout may provide some useful information and this function should behave identically in comparable situations. The grid.layout function has added the ability to specify a broader range of units for row heights and column widths, and allows for nested layouts (see viewport).

Author(s)

Paul Murrell

References

Murrell, P. R. (1999), Layouts: A Mechanism for Arranging Plots on a Page, Journal of Computational and Graphical Statistics, 8, 121–134.

See Also

Grid, grid.show.layout, viewport, layout

Examples

## A variety of layouts (some a bit mid-bending ...)
layout.torture()
## Demonstration of layout justification
grid.newpage()
testlay <- function(just="centre") {
  pushViewport(viewport(layout=grid.layout(1, 1, widths=unit(1, "inches"),
                          height=unit(0.25, "npc"),
                          just=just)))
  pushViewport(viewport(layout.pos.col=1, layout.pos.row=1))
  grid.rect()
  grid.text(paste(just, collapse="-"))
  popViewport(2)
}
testlay()
testlay(c("left", "top"))
testlay(c("right", "top"))
testlay(c("right", "bottom"))
testlay(c("left", "bottom"))
testlay(c("left"))
testlay(c("right"))
testlay(c("bottom"))
testlay(c("top"))


Draw Lines in a Grid Viewport

Description

These functions create and draw a series of lines.

Usage

grid.lines(x = unit(c(0, 1), "npc"),
          y = unit(c(0, 1), "npc"),
          default.units = "npc",
          arrow = NULL, name = NULL,
          gp=gpar(), draw = TRUE, vp = NULL)
linesGrob(x = unit(c(0, 1), "npc"),
          y = unit(c(0, 1), "npc"),
          default.units = "npc",
          arrow = NULL, name = NULL,
          gp=gpar(), vp = NULL)
grid.polyline(...)
polylineGrob(x = unit(c(0, 1), "npc"),
             y = unit(c(0, 1), "npc"),
             id=NULL, id.lengths=NULL,
             default.units = "npc",
             arrow = NULL, name = NULL,
             gp=gpar(), vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-values.
y | A numeric vector or unit object specifying y-values.
default.units | A string indicating the default units to use if x or y are only given as numeric vectors.
arrow | A list describing arrow heads to place at either end of the line, as produced by the arrow function.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).
id | A numeric vector used to separate locations in x and y into multiple lines. All locations with the same id belong to the same line.
id.lengths | A numeric vector used to separate locations in x and y into multiple lines. Specifies consecutive blocks of locations which make up separate lines.
... | Arguments passed to polylineGrob.

Details

The first two functions create a lines grob (a graphical object describing lines), and grid.lines draws the lines (if draw is TRUE).

The second two functions create or draw a polyline grob, which is just like a lines grob, except that there can be multiple distinct lines drawn.

Value

A lines grob or a polyline grob. grid.lines returns a lines grob invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport, arrow

Examples

grid.lines()
# Using id (NOTE: locations are not in consecutive blocks)
grid.newpage()
grid.polyline(x=c((0:4)/10, rep(.5, 5), (10:6)/10, rep(.5, 5)),
             y=c(rep(.5, 5), (10:6/10), rep(.5, 5), (0:4)/10),
             id=rep(1:5, 4),
             gp=gpar(col=1:5, lwd=3))
# Using id.lengths
grid.newpage()
grid.polyline(x=outer(c(0, .5, 1, .5), 5:1/5),
             y=outer(c(.5, 1, .5, 0), 5:1/5),
             id.lengths=rep(4, 5),
             gp=gpar(col=1:5, lwd=3))


Capture a Mouse Click

Description

Allows the user to click the mouse once within the current graphics device and returns the location of the mouse click within the current viewport, in the specified coordinate system.

Usage

grid.locator(unit = "native")

Arguments

unit The coordinate system in which to return the location of the mouse click. See the unit function for valid coordinate systems.

Details

This function is modal (like the graphics package function locator) so the command line and graphics drawing is blocked until the use has clicked the mouse in the current device.

Value

A unit object representing the location of the mouse click within the current viewport, in the specified coordinate system.
If the user did not click mouse button 1, the function (invisibly) returns NULL.

Author(s)

Paul Murrell

See Also

viewport, unit, locator in package graphics, and for an application see trellis.focus and trellis.identify in package lattice.

Examples

if (interactive()) {
  ## Need to write a more sophisticated unit as.character method
  unittrim <- function(unit) {
    sub("^([0-9]+|[0-9]+[.][0-9])[0-9]*", "\\1", as.character(unit))
  }
  do.click <- function(unit) {
    click.locn <- grid.locator(unit)
    grid.segments(unit.c(click.locn$x, unit(0, "npc")),
                  unit.c(unit(0, "npc"), click.locn$y),
                  click.locn$x, click.locn$y,
                  gp=gpar(lty="dashed", col="grey"))
    grid.points(click.locn$x, click.locn$y, pch=16, size=unit(1, "mm"))
    clickx <- unittrim(click.locn$x)
    clicky <- unittrim(click.locn$y)
    grid.text(paste("(", clickx, ", ", clicky, ")", sep=""),
              click.locn$x + unit(2, "mm"), click.locn$y,
              just="left")
  }
  do.click("inches")
  pushViewport(viewport(width=0.5, height=0.5,
                         xscale=c(0, 100), yscale=c(0, 10)))
  grid.rect()
  grid.xaxis()
  grid.yaxis()
  do.click("native")
  popViewport()
}


Move or Draw to a Specified Position

Description

Grid has the notion of a current location. These functions sets that location.

Usage

grid.move.to(x = 0, y = 0, default.units = "npc", name = NULL,
             draw = TRUE, vp = NULL)

moveToGrob(x = 0, y = 0, default.units = "npc", name = NULL, vp = NULL)

grid.line.to(x = 1, y = 1, default.units = "npc",
             arrow = NULL, name = NULL,
             gp = gpar(), draw = TRUE, vp = NULL)

lineToGrob(x = 1, y = 1, default.units = "npc", arrow = NULL,
           name = NULL, gp = gpar(), vp = NULL)

Arguments

x | A numeric value or a unit object specifying an x-value.
y | A numeric value or a unit object specifying a y-value.
default.units | A string indicating the default units to use if x or y are only given as numeric values.
arrow | A list describing arrow heads to place at either end of the line, as produced by the arrow function.
name | A character identifier.
draw | A logical value indicating whether graphics output should be produced.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A Grid viewport object (or NULL).

Details

Both functions create a move.to/line.to grob (a graphical object describing a move-to/line-to), but only grid.move.to/line.to() draws the move.to/line.to (and then only if draw is TRUE).

Value

A move.to/line.to grob. grid.move.to/line.to() returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport, arrow

Examples

grid.newpage()
grid.move.to(0.5, 0.5)
grid.line.to(1, 1)
grid.line.to(0.5, 0)
pushViewport(viewport(x=0, y=0, w=0.25, h=0.25, just=c("left", "bottom")))
grid.rect()
grid.grill()
grid.line.to(0.5, 0.5)
popViewport()


Move to a New Page on a Grid Device

Description

This function erases the current device or moves to a new page.

Usage

grid.newpage(recording = TRUE)

Arguments

recording A logical value to indicate whether the new-page operation should be saved onto the Grid display list.

Details

There is a hook called "grid.newpage" (see setHook) which is used in the testing code to annotate the new page. The hook function(s) are called with no argument. (If the value is a character string, get is called on it from within the grid namespace.)

Value

None.

Author(s)

Paul Murrell

See Also

Grid


Pack an Object within a Frame

Description

This functions, together with grid.frame and frameGrob are part of a GUI-builder-like interface to constructing graphical images. The idea is that you create a frame with grid.frame or frameGrob then use this functions to pack objects into the frame.

Usage

grid.pack(gPath, grob, redraw = TRUE, side = NULL,
          row = NULL, row.before = NULL, row.after = NULL,
          col = NULL, col.before = NULL, col.after = NULL,
          width = NULL, height = NULL,
          force.width = FALSE, force.height = FALSE, border = NULL,
          dynamic = FALSE)

packGrob(frame, grob, side = NULL,
          row = NULL, row.before = NULL, row.after = NULL,
          col = NULL, col.before = NULL, col.after = NULL,
          width = NULL, height = NULL,
          force.width = FALSE, force.height = FALSE, border = NULL,
          dynamic = FALSE)

Arguments

gPath | A gPath object, which specifies a frame on the display list.
frame | An object of class frame, typically the output from a call to grid.frame.
grob | An object of class grob. The object to be packed.
redraw | A boolean indicating whether the output should be updated.
side | One of "left", "top", "right", "bottom" to indicate which side to pack the object on.
row | Which row to add the object to. Must be between 1 and the-number-of-rows-currently-in-the-frame + 1, or NULL in which case the object occupies all rows.
row.before | Add the object to a new row just before this row.
row.after | Add the object to a new row just after this row.
col | Which col to add the object to. Must be between 1 and the-number-of-cols-currently-in-the-frame + 1, or NULL in which case the object occupies all cols.
col.before | Add the object to a new col just before this col.
col.after | Add the object to a new col just after this col.
width | Specifies the width of the column that the object is added to (rather than allowing the width to be taken from the object).
height | Specifies the height of the row that the object is added to (rather than allowing the height to be taken from the object).
force.width | A logical value indicating whether the width of the column that the grob is being packed into should be EITHER the width specified in the call to grid.pack OR the maximum of that width and the pre-existing width.
force.height | A logical value indicating whether the height of the column that the grob is being packed into should be EITHER the height specified in the call to grid.pack OR the maximum of that height and the pre-existing height.
border | A unit object of length 4 indicating the borders around the object.
dynamic | If the width/height is taken from the grob being packed, this boolean flag indicates whether the grobwidth/height unit refers directly to the grob, or uses a gPath to the grob. In the latter case, changes to the grob will trigger a recalculation of the width/height.

Details

packGrob modifies the given frame grob and returns the modified frame grob.

grid.pack destructively modifies a frame grob on the display list (and redraws the display list if redraw is TRUE).

These are (meant to be) very flexible functions. There are many different ways to specify where the new object is to be added relative to the objects already in the frame. The function checks that the specification is not self-contradictory.

NOTE that the width/height of the row/col that the object is added to is taken from the object itself unless the width/height is specified.

Value

packGrob returns a frame grob, but grid.pack returns NULL.

Author(s)

Paul Murrell

See Also

grid.frame, grid.place, grid.edit, and gPath.


Place an Object within a Frame

Description

These functions provide a simpler (and faster) alternative to the grid.pack() and packGrob functions. They can be used to place objects within the existing rows and columns of a frame layout. They do not provide the ability to add new rows and columns nor do they affect the heights and widths of the rows and columns.

Usage

grid.place(gPath, grob, row = 1, col = 1, redraw = TRUE)
placeGrob(frame, grob, row = NULL, col = NULL)

Arguments

gPath | A gPath object, which specifies a frame on the display list.
frame | An object of class frame, typically the output from a call to grid.frame.
grob | An object of class grob. The object to be placed.
row | Which row to add the object to. Must be between 1 and the-number-of-rows-currently-in-the-frame.
col | Which col to add the object to. Must be between 1 and the-number-of-cols-currently-in-the-frame.
redraw | A boolean indicating whether the output should be updated.

Details

placeGrob modifies the given frame grob and returns the modified frame grob.

grid.place destructively modifies a frame grob on the display list (and redraws the display list if redraw is TRUE).

Value

placeGrob returns a frame grob, but grid.place returns NULL.

Author(s)

Paul Murrell

See Also

grid.frame, grid.pack, grid.edit, and gPath.


A Simple Plot and Legend Demo

Description

This function is just a wrapper for a simple demonstration of how a basic plot and legend can be drawn from scratch using grid.

Usage

grid.plot.and.legend()

Author(s)

Paul Murrell

Examples

grid.plot.and.legend()


Draw Data Symbols

Description

These functions create and draw data symbols.

Usage

grid.points(x = stats::runif(10),
            y = stats::runif(10),
            pch = 1, size = unit(1, "char"),
            default.units = "native", name = NULL,
            gp=gpar(), draw = TRUE, vp = NULL)
pointsGrob(x = stats::runif(10),
            y = stats::runif(10),
            pch = 1, size = unit(1, "char"),
            default.units = "native", name = NULL,
            gp=gpar(), vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-values.
y | A numeric vector or unit object specifying y-values.
pch | A numeric or character vector indicating what sort of plotting symbol to use.
size | A unit object specifying the size of the plotting symbols.
default.units | A string indicating the default units to use if x or y are only given as numeric vectors.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create a points grob (a graphical object describing points), but only grid.points draws the points (and then only if draw is TRUE).

Value

A points grob. grid.points returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport


Draw a Polygon

Description

These functions create and draw a polygon. The final point will automatically be connected to the initial point.

Usage

grid.polygon(x=c(0, 0.5, 1, 0.5), y=c(0.5, 1, 0.5, 0),
             id=NULL, id.lengths=NULL,
             default.units="npc", name=NULL,
             gp=gpar(), draw=TRUE, vp=NULL)
polygonGrob(x=c(0, 0.5, 1, 0.5), y=c(0.5, 1, 0.5, 0),
             id=NULL, id.lengths=NULL,
             default.units="npc", name=NULL,
             gp=gpar(), vp=NULL)

Arguments

x | A numeric vector or unit object specifying x-locations.
y | A numeric vector or unit object specifying y-locations.
id | A numeric vector used to separate locations in x and y into multiple polygons. All locations with the same id belong to the same polygon.
id.lengths | A numeric vector used to separate locations in x and y into multiple polygons. Specifies consecutive blocks of locations which make up separate polygons.
default.units | A string indicating the default units to use if x, y, width, or height are only given as numeric vectors.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create a polygon grob (a graphical object describing a polygon), but only grid.polygon draws the polygon (and then only if draw is TRUE).

Value

A grob object.

Author(s)

Paul Murrell

See Also

Grid, viewport

Examples

grid.polygon()
# Using id (NOTE: locations are not in consecutive blocks)
grid.newpage()
grid.polygon(x=c((0:4)/10, rep(.5, 5), (10:6)/10, rep(.5, 5)),
             y=c(rep(.5, 5), (10:6/10), rep(.5, 5), (0:4)/10),
             id=rep(1:5, 4),
             gp=gpar(fill=1:5))
# Using id.lengths
grid.newpage()
grid.polygon(x=outer(c(0, .5, 1, .5), 5:1/5),
             y=outer(c(.5, 1, .5, 0), 5:1/5),
             id.lengths=rep(4, 5),
             gp=gpar(fill=1:5))


Generate a Sensible Set of Breakpoints

Description

Produces a pretty set of breakpoints within the range given.

Usage

grid.pretty(range)

Arguments

range A numeric vector

Value

A numeric vector of breakpoints.

Author(s)

Paul Murrell


Prompt before new page

Description

This function can be used to control whether the user is prompted before starting a new page of output.

Usage

grid.prompt(ask)

Arguments

ask a logical value. If TRUE, the user is prompted before a new page of output is started.

Value

The current prompt setting before any new setting is applied.

Author(s)

Paul Murrell

See Also

grid.newpage


Encapsulate calculations and drawing

Description

Evaluates an expression that includes both calculatons and drawing that depends on the calculations so that both the calculations and the drawing will be rerun when the scene is redrawn (e.g., device resize or editing).

Intended only for expert use.

Usage

recordGrob(expr, list, name=NULL, gp=NULL, vp=NULL)
grid.record(expr, list, name=NULL, gp=NULL, vp=NULL)

Arguments

expr | object of mode expression or call or an “unevaluated expression”.
list | a list defining the environment in which expr is to be evaluated.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A Grid viewport object (or NULL).

Details

A grob is created of special class "recordedGrob" (and drawn, in the case of grid.record). The drawDetails method for this class evaluates the expression with the list as the evaluation environment (and the grid Namespace as the parent of that environment).

Note

This function must be used instead of the function recordGraphics; all of the dire warnings about using recordGraphics responsibly also apply here.

Author(s)

Paul Murrell

See Also

recordGraphics

Examples

grid.record({
              w <- convertWidth(unit(1, "inches"), "npc")
                      grid.rect(width=w)
            },
            list())


Draw rectangles

Description

These functions create and draw rectangles.

Usage

grid.rect(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
          width = unit(1, "npc"), height = unit(1, "npc"),
          just = "centre", hjust = NULL, vjust = NULL,
          default.units = "npc", name = NULL,
          gp=gpar(), draw = TRUE, vp = NULL)
rectGrob(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
         width = unit(1, "npc"), height = unit(1, "npc"),
         just = "centre", hjust = NULL, vjust = NULL,
         default.units = "npc", name = NULL,
         gp=gpar(), vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-location.
y | A numeric vector or unit object specifying y-location.
width | A numeric vector or unit object specifying width.
height | A numeric vector or unit object specifying height.
just | The justification of the rectangle relative to its (x, y) location. If there are two values, the first value specifes horizontal justification and the second value specifies vertical justification. Possible string values are: "left", "right", "centre", "center", "bottom", and "top". For numeric values, 0 means left alignment and 1 means right alignment.
hjust | A numeric vector specifying horizontal justification. If specified, overrides the just setting.
vjust | A numeric vector specifying vertical justification. If specified, overrides the just setting.
default.units | A string indicating the default units to use if x, y, width, or height are only given as numeric vectors.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create a rect grob (a graphical object describing rectangles), but only grid.rect draws the rectangles (and then only if draw is TRUE).

Value

A rect grob. grid.rect returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport


Refresh the current grid scene

Description

Replays the current grid display list.

Usage

grid.refresh()

Author(s)

Paul Murrell


Remove a Grid Graphical Object

Description

Remove a grob from a gTree or a descendant of a gTree.

Usage

grid.remove(gPath, warn = TRUE, strict  =  FALSE, grep = FALSE,
            global = FALSE, allDevices = FALSE, redraw = TRUE)

removeGrob(gTree, gPath, strict = FALSE, grep = FALSE,
           global = FALSE, warn = TRUE)

Arguments

gTree | A gTree object.
gPath | A gPath object. For grid.remove this specifyies a gTree on the display list. For removeGrob this specifies a descendant of the specified gTree.
strict | A boolean indicating whether the gPath must be matched exactly.
grep | A boolean indicating whether the gPath should be treated as a regular expression. Values are recycled across elements of the gPath (e.g., c(TRUE, FALSE) means that every odd element of the gPath will be treated as a regular expression).
global | A boolean indicating whether the function should affect just the first match of the gPath, or whether all matches should be affected.
allDevices | A boolean indicating whether all open devices should be searched for matches, or just the current device. NOT YET IMPLEMENTED.
warn | A logical to indicate whether failing to find the specified grob should trigger an error.
redraw | A logical value to indicate whether to redraw the grob.

Details

removeGrob copies the specified grob and returns a modified grob.

grid.remove destructively modifies a grob on the display list. If redraw is TRUE it then redraws everything to reflect the change.

Value

removeGrob returns a grob object; grid.remove returns NULL.

Author(s)

Paul Murrell

See Also

grob, getGrob, removeGrob, removeGrob.


Draw Line Segments

Description

These functions create and draw line segments.

Usage

grid.segments(x0 = unit(0, "npc"), y0 = unit(0, "npc"),
              x1 = unit(1, "npc"), y1 = unit(1, "npc"),
              default.units = "npc",
              arrow = NULL,
              name = NULL, gp = gpar(), draw = TRUE, vp = NULL)
segmentsGrob(x0 = unit(0, "npc"), y0 = unit(0, "npc"),
              x1 = unit(1, "npc"), y1 = unit(1, "npc"),
              default.units = "npc",
              arrow = NULL, name = NULL, gp = gpar(), vp = NULL)

Arguments

x0 | Numeric indicating the starting x-values of the line segments.
y0 | Numeric indicating the starting y-values of the line segments.
x1 | Numeric indicating the stopping x-values of the line segments.
y1 | Numeric indicating the stopping y-values of the line segments.
default.units | A string.
arrow | A list describing arrow heads to place at either end of the line segments, as produced by the arrow function.
name | A character identifier.
gp | An object of class gpar.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL)

Details

Both functions create a segments grob (a graphical object describing segments), but only grid.segments draws the segments (and then only if draw is TRUE).

Value

A segments grob. grid.segments returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport, arrow


Set a Grid Graphical Object

Description

Replace a grob or a descendant of a grob.

Usage

grid.set(gPath, newGrob, strict = FALSE, grep = FALSE,
         redraw = TRUE)

setGrob(gTree, gPath, newGrob, strict = FALSE, grep = FALSE)

Arguments

gTree | A gTree object.
gPath | A gPath object. For grid.set this specifyies a grob on the display list. For setGrob this specifies a descendant of the specified gTree.
newGrob | A grob object.
strict | A boolean indicating whether the gPath must be matched exactly.
grep | A boolean indicating whether the gPath should be treated as a regular expression. Values are recycled across elements of the gPath (e.g., c(TRUE, FALSE) means that every odd element of the gPath will be treated as a regular expression).
redraw | A logical value to indicate whether to redraw the grob.

Details

setGrob copies the specified grob and returns a modified grob.

grid.set destructively replaces a grob on the display list. If redraw is TRUE it then redraws everything to reflect the change.

These functions should not normally be called by the user.

Value

setGrob returns a grob object; grid.set returns NULL.

Author(s)

Paul Murrell

See Also

grid.grob.


Draw a Diagram of a Grid Layout

Description

This function uses Grid graphics to draw a diagram of a Grid layout.

Usage

grid.show.layout(l, newpage=TRUE, bg = "light grey",
             cell.border = "blue", cell.fill = "light blue",
             cell.label = TRUE, label.col = "blue",
             unit.col = "red", vp = NULL)

Arguments

l | A Grid layout object.
newpage | A logical value indicating whether to move on to a new page before drawing the diagram.
bg | The colour used for the background.
cell.border | The colour used to draw the borders of the cells in the layout.
cell.fill | The colour used to fill the cells in the layout.
cell.label | A logical indicating whether the layout cells should be labelled.
label.col | The colour used for layout cell labels.
unit.col | The colour used for labelling the widths/heights of columns/rows.
vp | A Grid viewport object (or NULL).

Details

A viewport is created within vp to provide a margin for annotation, and the layout is drawn within that new viewport. The margin is filled with light grey, the new viewport is filled with white and framed with a black border, and the layout regions are filled with light blue and framed with a blue border. The diagram is annotated with the widths and heights (including units) of the columns and rows of the layout using red text. (All colours are defaults and may be customised via function arguments.)

Value

None.

Author(s)

Paul Murrell

See Also

Grid, viewport, grid.layout

Examples

## Diagram of a simple layout
grid.show.layout(grid.layout(4,2,
                     heights=unit(rep(1, 4),
                                  c("lines", "lines", "lines", "null")),
                     widths=unit(c(1, 1), "inches")))


Draw a Diagram of a Grid Viewport

Description

This function uses Grid graphics to draw a diagram of a Grid viewport.

Usage

grid.show.viewport(v, parent.layout = NULL, newpage = TRUE,
                   border.fill="light grey",
                   vp.col="blue", vp.fill="light blue",
                   scale.col="red",
                   vp = NULL)

Arguments

v | A Grid viewport object.
parent.layout | A grid layout object. If this is not NULL and the viewport given in v has its location specified relative to the layout, then the diagram shows the layout and which cells v occupies within the layout.
newpage | A logical value to indicate whether to move to a new page before drawing the diagram.
border.fill | Colour to fill the border margin.
vp.col | Colour for the border of the viewport region.
vp.fill | Colour to fill the viewport region.
scale.col | Colour to draw the viewport axes.
vp | A Grid viewport object (or NULL).

Details

A viewport is created within vp to provide a margin for annotation, and the diagram is drawn within that new viewport. By default, the margin is filled with light grey, the new viewport is filled with white and framed with a black border, and the viewport region is filled with light blue and framed with a blue border. The diagram is annotated with the width and height (including units) of the viewport, the (x, y) location of the viewport, and the x- and y-scales of the viewport, using red lines and text.

Value

None.

Author(s)

Paul Murrell

See Also

Grid, viewport

Examples

## Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
                            w=unit(1, "inches"), h=unit(1, "inches")))
grid.show.viewport(viewport(layout.pos.row=2, layout.pos.col=2:3),
                   grid.layout(3, 4))


Draw Text

Description

These functions create and draw text.

Usage

grid.text(label, x = unit(0.5, "npc"), y = unit(0.5, "npc"),
          just = "centre", hjust = NULL, vjust = NULL, rot = 0,
          check.overlap = FALSE, default.units = "npc",
          name = NULL, gp = gpar(), draw = TRUE, vp = NULL)

textGrob(label, x = unit(0.5, "npc"), y = unit(0.5, "npc"),
          just = "centre", hjust = NULL, vjust = NULL, rot = 0,
          check.overlap = FALSE, default.units = "npc",
          name = NULL, gp = gpar(), vp = NULL)

Arguments

label | A vector of strings or expressions to draw.
x | A numeric vector or unit object specifying x-values.
y | A numeric vector or unit object specifying y-values.
just | The justification of the text relative to its (x, y) location. If there are two values, the first value specifes horizontal justification and the second value specifies vertical justification. Possible string values are: "left", "right", "centre", "center", "bottom", and "top". For numeric values, 0 means left alignment and 1 means right alignment.
hjust | A numeric vector specifying horizontal justification. If specified, overrides the just setting.
vjust | A numeric vector specifying vertical justification. If specified, overrides the just setting.
rot | The angle to rotate the text.
check.overlap | A logical value to indicate whether to check for and omit overlapping text.
default.units | A string indicating the default units to use if x or y are only given as numeric vectors.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport object (or NULL).

Details

Both functions create a text grob (a graphical object describing text), but only grid.text draws the text (and then only if draw is TRUE).

If the label argument is an expression, the output is formatted as a mathematical annotation, as for base graphics text.

Value

A text grob. grid.text returns the value invisibly.

Author(s)

Paul Murrell

See Also

Grid, viewport

Examples

grid.newpage()
x <- stats::runif(20)
y <- stats::runif(20)
rot <- stats::runif(20, 0, 360)
grid.text("SOMETHING NICE AND BIG", x=x, y=y, rot=rot,
          gp=gpar(fontsize=20, col="grey"))
grid.text("SOMETHING NICE AND BIG", x=x, y=y, rot=rot,
          gp=gpar(fontsize=20), check=TRUE)
grid.newpage()
draw.text <- function(just, i, j) {
  grid.text("ABCD", x=x[j], y=y[i], just=just)
  grid.text(deparse(substitute(just)), x=x[j], y=y[i] + unit(2, "lines"),
            gp=gpar(col="grey", fontsize=8))
}
x <- unit(1:4/5, "npc")
y <- unit(1:4/5, "npc")
grid.grill(h=y, v=x, gp=gpar(col="grey"))
draw.text(c("bottom"), 1, 1)
draw.text(c("left", "bottom"), 2, 1)
draw.text(c("right", "bottom"), 3, 1)
draw.text(c("centre", "bottom"), 4, 1)
draw.text(c("centre"), 1, 2)
draw.text(c("left", "centre"), 2, 2)
draw.text(c("right", "centre"), 3, 2)
draw.text(c("centre", "centre"), 4, 2)
draw.text(c("top"), 1, 3)
draw.text(c("left", "top"), 2, 3)
draw.text(c("right", "top"), 3, 3)
draw.text(c("centre", "top"), 4, 3)
draw.text(c(), 1, 4)
draw.text(c("left"), 2, 4)
draw.text(c("right"), 3, 4)
draw.text(c("centre"), 4, 4)


Draw an X-Axis

Description

These functions create and draw an x-axis.

Usage

grid.xaxis(at = NULL, label = TRUE, main = TRUE,
           edits = NULL, name = NULL,
           gp = gpar(), draw = TRUE, vp = NULL)

xaxisGrob(at = NULL, label = TRUE, main = TRUE,
          edits = NULL, name = NULL,
          gp = gpar(), vp = NULL)

Arguments

at | A numeric vector of x-value locations for the tick marks.
label | A logical value indicating whether to draw the labels on the tick marks, or an expression or string vector which specify the labels to use. If not logical, must be the same length as the at argument.
main | A logical value indicating whether to draw the axis at the bottom (TRUE) or at the top (FALSE) of the viewport.
edits | A gEdit or gEditList containing edit operations to apply (to the children of the axis) when the axis is first created and during redrawing whenever at is NULL.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport obect (or NULL).

Details

Both functions create an xaxis grob (a graphical object describing an xaxis), but only grid.xaxis draws the xaxis (and then only if draw is TRUE).

Value

An xaxis grob. grid.xaxis returns the value invisibly.

Children

If the at slot of an xaxis grob is not NULL then the xaxis will have the following children:

major
representing the line at the base of the tick marks.
ticks
representing the tick marks.
labels
representing the tick labels.

If the at slot is NULL then there are no children and ticks are drawn based on the current viewport scale.

Author(s)

Paul Murrell

See Also

Grid, viewport, grid.yaxis


Draw an Xspline

Description

These functions create and draw an xspline, a curve drawn relative to control points.

Usage

grid.xspline(...)
xsplineGrob(x = c(0, 0.5, 1, 0.5), y = c(0.5, 1, 0.5, 0),
            id = NULL, id.lengths = NULL,
            default.units = "npc",
            shape = 0, open = TRUE, arrow = NULL, repEnds = TRUE,
            name = NULL, gp = gpar(), vp = NULL)

Arguments

x | A numeric vector or unit object specifying x-locations of spline control points.
y | A numeric vector or unit object specifying y-locations of spline control points.
id | A numeric vector used to separate locations in x and y into multiple xsplines. All locations with the same id belong to the same xspline.
id.lengths | A numeric vector used to separate locations in x and y into multiple xspline. Specifies consecutive blocks of locations which make up separate xsplines.
default.units | A string indicating the default units to use if x or y are only given as numeric vectors.
shape | A numeric vector of values between -1 and 1, which control the shape of the spline relative to the control points.
open | A logical value indicating whether the spline is a line or a closed shape.
arrow | A list describing arrow heads to place at either end of the xspline, as produced by the arrow function.
repEnds | A logical value indicating whether the first and last control points should be replicated for drawing the curve (see Details below).
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
vp | A Grid viewport object (or NULL).
... | Arguments to be passed to xsplineGrob.

Details

Both functions create an xspline grob (a graphical object describing an xspline), but only grid.xspline draws the xspline.

An xspline is a line drawn relative to control points. For each control point, the line may pass through (interpolate) the control point or it may only approach (approximate) the control point; the behaviour is determined by a shape parameter for each control point.

If the shape parameter is greater than zero, the spline approximates the control points (and is very similar to a cubic B-spline when the shape is 1). If the shape parameter is less than zero, the spline interpolates the control points (and is very similar to a Catmull-Rom spline when the shape is -1). If the shape parameter is 0, the spline forms a sharp corner at that control point.

For open xsplines, the start and end control points must have a shape of 0 (and non-zero values are silently converted to zero without warning).

For open xsplines, by default the start and end control points are actually replicated before the curve is drawn. A curve is drawn between (interpolating or approximating) the second and third of each set of four control points, so this default behaviour ensures that the resulting curve starts at the first control point you have specified and ends at the last control point. The default behaviour can be turned off via the repEnds argument, in which case the curve that is drawn starts (approximately) at the second control point and ends (approximately) at thefirst and second-to-last control point.

The repEnds argument is ignored for closed xsplines.

Missing values are not allowed for x and y (i.e., it is not valid for a control point to be missing).

For closed xsplines, a curve is automatically drawn between the final control point and the initial control point.

Value

A grob object.

References

Blanc, C. and Schlick, C. (1995), "X-splines : A Spline Model Designed for the End User", in Proceedings of SIGGRAPH 95.

See Also

Grid, viewport, \code{arrow}

Examples

x <- c(0.25, 0.25, 0.75, 0.75)
y <- c(0.25, 0.75, 0.75, 0.25)

xsplineTest <- function(s, i, j, open) {
  pushViewport(viewport(layout.pos.col=j, layout.pos.row=i))
  grid.points(x, y, default.units="npc", pch=16, size=unit(2, "mm"))
  grid.xspline(x, y, shape=s, open=open, gp=gpar(fill="grey"))
  grid.text(s, gp=gpar(col="grey"),
            x=unit(x, "npc") + unit(c(-1, -1, 1, 1), "mm"),
            y=unit(y, "npc") + unit(c(-1, 1, 1, -1), "mm"),
            hjust=c(1, 1, 0, 0),
            vjust=c(1, 0, 0, 1))
  popViewport()
}

pushViewport(viewport(width=.5, x=0, just="left",
                      layout=grid.layout(3, 3, respect=TRUE)))
pushViewport(viewport(layout.pos.row=1))
grid.text("Open Splines", y=1, just="bottom")
popViewport()
xsplineTest(c(0, -1, -1, 0), 1, 1, TRUE)
xsplineTest(c(0, -1,  0, 0), 1, 2, TRUE)
xsplineTest(c(0, -1,  1, 0), 1, 3, TRUE)
xsplineTest(c(0,  0, -1, 0), 2, 1, TRUE)
xsplineTest(c(0,  0,  0, 0), 2, 2, TRUE)
xsplineTest(c(0,  0,  1, 0), 2, 3, TRUE)
xsplineTest(c(0,  1, -1, 0), 3, 1, TRUE)
xsplineTest(c(0,  1,  0, 0), 3, 2, TRUE)
xsplineTest(c(0,  1,  1, 0), 3, 3, TRUE)
popViewport()
pushViewport(viewport(width=.5, x=1, just="right",
                      layout=grid.layout(3, 3, respect=TRUE)))
pushViewport(viewport(layout.pos.row=1))
grid.text("Closed Splines", y=1, just="bottom")
popViewport()
xsplineTest(c(-1, -1, -1, -1), 1, 1, FALSE)
xsplineTest(c(-1, -1,  0, -1), 1, 2, FALSE)
xsplineTest(c(-1, -1,  1, -1), 1, 3, FALSE)
xsplineTest(c( 0,  0, -1,  0), 2, 1, FALSE)
xsplineTest(c( 0,  0,  0,  0), 2, 2, FALSE)
xsplineTest(c( 0,  0,  1,  0), 2, 3, FALSE)
xsplineTest(c( 1,  1, -1,  1), 3, 1, FALSE)
xsplineTest(c( 1,  1,  0,  1), 3, 2, FALSE)
xsplineTest(c( 1,  1,  1,  1), 3, 3, FALSE)
popViewport()


Draw a Y-Axis

Description

These functions create and draw a y-axis.

Usage

grid.yaxis(at = NULL, label = TRUE, main = TRUE,
           edits = NULL, name = NULL,
           gp = gpar(), draw = TRUE, vp = NULL)

yaxisGrob(at = NULL, label = TRUE, main = TRUE,
          edits = NULL, name = NULL,
          gp = gpar(), vp = NULL)

Arguments

at | A numeric vector of y-value locations for the tick marks.
label | A logical value indicating whether to draw the labels on the tick marks, or an expression or string vector which specify the labels to use. If not logical, must be the same length as the at argument.
main | A logical value indicating whether to draw the axis at the left (TRUE) or at the right (FALSE) of the viewport.
edits | A gEdit or gEditList containing edit operations to apply (to the children of the axis) when the axis is first created and during redrawing whenever at is NULL.
name | A character identifier.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
draw | A logical value indicating whether graphics output should be produced.
vp | A Grid viewport obect (or NULL).

Details

Both functions create a yaxis grob (a graphical object describing a yaxis), but only grid.yaxis draws the yaxis (and then only if draw is TRUE).

Value

A yaxis grob. grid.yaxis returns the value invisibly.

Children

If the at slot of an xaxis grob is not NULL then the xaxis will have the following children:

major
representing the line at the base of the tick marks.
ticks
representing the tick marks.
labels
representing the tick labels.

If the at slot is NULL then there are no children and ticks are drawn based on the current viewport scale.

Author(s)

Paul Murrell

See Also

Grid, viewport, grid.xaxis


Generate a Name for a Grob

Description

This function generates a unique (within-session) name for a grob, based on the grob's class.

Usage

grobName(grob = NULL, prefix = "GRID")

Arguments

grob | A grob object or NULL.
prefix | The prefix part of the name.

Value

A character string of the form prefix.class(grob).index

Author(s)

Paul Murrell


Create a Unit Describing the Width of a Grob

Description

These functions create a unit object describing the width or height of a grob. They are generic.

Usage

grobWidth(x)
grobHeight(x)

Arguments

x A grob object.

Value

A unit object.

Author(s)

Paul Murrell

See Also

unit and stringWidth


Create a Unit Describing a Grob Boundary Location

Description

These functions create a unit object describing a location somewhere on the boundary of a grob. They are generic.

Usage

grobX(x, theta)
grobY(x, theta)

Arguments

x | A grob, or gList, or gTree, or gPath.
theta | An angle indicating where the location is on the grob boundary. Can be one of "east", "north", "west", or "south", which correspond to angles 0, 90, 180, and 270, respectively.

Details

The angle is anti-clockwise with zero corresponding to a line with an origin centred between the extreme points of the shape, and pointing at 3 o'clock.

If the grob describes a single shape, the boundary value should correspond to the exact edge of the shape.

If the grob describes multiple shapes, in most cases, the boundary value will correspond to the edge of a bounding box around all of the shapes. The exception to this is a polygon grob describing multiple polygons; in that case, the edge corresponds to a convex hull around all points of all polygons described by the grob.

Value

A unit object.

Author(s)

Paul Murrell

See Also

unit and grobWidth


Create a Viewport with a Standard Plot Layout

Description

This is a convenience function for producing a viewport with the common S-style plot layout – i.e., a central plot region surrounded by margins given in terms of a number of lines of text.

Usage

plotViewport(margins=c(5.1, 4.1, 4.1, 2.1), ...)

Arguments

margins | A numeric vector interpreted in the same way as par(mar) in base graphics.
... | All other arguments will be passed to a call to the viewport() function.

Value

A grid viewport object.

Author(s)

Paul Murrell

See Also

viewport and dataViewport.


Pop a Viewport off the Grid Viewport Stack

Description

Grid maintains a viewport stack — a list of nested drawing contexts.

This function makes the parent of the specified viewport the new default viewport.

Usage

pop.viewport(n=1, recording=TRUE)

Arguments

n | An integer giving the number of viewports to pop. Defaults to 1.
recording | A logical value to indicate whether the set-viewport operation should be recorded on the Grid display list.

Value

None.

Warning

This function has been deprecated. Please use popViewport instead.

Author(s)

Paul Murrell

See Also

push.viewport.


Push a Viewport onto the Grid Viewport Stack

Description

Grid maintains a viewport stack — a list of nested drawing contexts.

This function makes the specified viewport the default viewport and makes its parent the previous default viewport (i.e., nests the specified context within the previous default context).

Usage

push.viewport(..., recording=TRUE)

Arguments

... | One or more objects of class "viewport", or NULL.
recording | A logical value to indicate whether the set-viewport operation should be recorded on the Grid display list.

Value

None.

Warning

This function has been deprecated. Please use pushViewport instead.

Author(s)

Paul Murrell

See Also

pop.viewport.


Create a Unit Describing the Width of a String

Description

These functions create a unit object describing the width or height of a string.

Usage

stringWidth(string)
stringHeight(string)

Arguments

string A character vector.

Value

A unit object.

Author(s)

Paul Murrell

See Also

unit and grobWidth


Function to Create a Unit Object

Description

This function creates a unit object — a vector of unit values. A unit value is typically just a single numeric value with an associated unit.

Usage

unit(x, units, data=NULL)

Arguments

x | A numeric vector.
units | A character vector specifying the units for the corresponding numeric values.
data | This argument is used to supply extra information for special unit types.

Details

Unit objects allow the user to specify locations and dimensions in a large number of different coordinate systems. All drawing occurs relative to a viewport and the units specifies what coordinate system to use within that viewport.

Possible units (coordinate systems) are:

"npc"
Normalised Parent Coordinates (the default). The origin of the viewport is (0, 0) and the viewport has a width and height of 1 unit. For example, (0.5, 0.5) is the centre of the viewport.
"cm"
Centimetres.
"inches"
Inches. 1 in = 2.54 cm.
"mm"
Millimetres. 10 mm = 1 cm.
"points"
Points. 72.27 pt = 1 in.
"picas"
Picas. 1 pc = 12 pt.
"bigpts"
Big Points. 72 bp = 1 in.
"dida"
Dida. 1157 dd = 1238 pt.
"cicero"
Cicero. 1 cc = 12 dd.
"scaledpts"
Scaled Points. 65536 sp = 1 pt.
"lines"
Lines of text. Locations and dimensions are in terms of multiples of the default text size of the viewport (as specified by the viewport's fontsize and lineheight).
"char"
Multiples of nominal font height of the viewport (as specified by the viewport's fontsize).
"native"
Locations and dimensions are relative to the viewport's xscale and yscale.
"snpc"
Square Normalised Parent Coordinates. Same as Normalised Parent Coordinates, except gives the same answer for horizontal and vertical locations/dimensions. It uses the lesser of npc-width and npc-height. This is useful for making things which are a proportion of the viewport, but have to be square (or have a fixed aspect ratio).
"strwidth"
Multiples of the width of the string specified in the data argument. The font size is determined by the pointsize of the viewport.
"strheight"
Multiples of the height of the string specified in the data argument. The font size is determined by the pointsize of the viewport.
"grobwidth"
Multiples of the width of the grob specified in the data argument.
"grobheight"
Multiples of the height of the grob specified in the data argument.

A special units value of "null" is also allowed, but only makes sense when used in specifying widths of columns or heights of rows in grid layouts (see grid.layout).

The data argument must be a list when the unit.length() is greater than 1. For example, unit(rep(1, 3), c("npc", "strwidth", "inches"), data=list(NULL, "my string", NULL)).

It is possible to subset unit objects in the normal way (e.g., unit(1:5, "npc")[2:4]), but a special function unit.c is provided for combining unit objects.

Certain arithmetic and summary operations are defined for unit objects. In particular, it is possible to add and subtract unit objects (e.g., unit(1, "npc") - unit(1, "inches")), and to specify the minimum or maximum of a list of unit objects (e.g., min(unit(0.5, "npc"), unit(1, "inches"))).

Value

An object of class "unit".

WARNING

There is a special function unit.c for concatenating several unit objects.

The c function will not give the right answer.

There used to be "mylines", "mychar", "mystrwidth", "mystrheight" units. These will still be accepted, but work exactly the same as "lines", "char", "strwidth", "strheight".

Author(s)

Paul Murrell

See Also

unit.c

Examples

unit(1, "npc")
unit(1:3/4, "npc")
unit(1:3/4, "npc") + unit(1, "inches")
min(unit(0.5, "npc"), unit(1, "inches"))
unit.c(unit(0.5, "npc"), unit(2, "inches") + unit(1:3/4, "npc"),
       unit(1, "strwidth", "hi there"))


Combine Unit Objects

Description

This function produces a new unit object by combining the unit objects specified as arguments.

Usage

unit.c(...)

Arguments

... An arbitrary number of unit objects.

Value

An object of class unit.

Author(s)

Paul Murrell

See Also

unit.


Length of a Unit Object

Description

The length of a unit object is defined as the number of unit values in the unit object.

This function has been deprecated in favour of a unit method for the generic length function.

Usage

unit.length(unit)

Arguments

unit A unit object.

Value

An integer value.

Author(s)

Paul Murrell

See Also

unit

Examples

length(unit(1:3, "npc"))
length(unit(1:3, "npc") + unit(1, "inches"))
length(max(unit(1:3, "npc") + unit(1, "inches")))
length(max(unit(1:3, "npc") + unit(1, "strwidth", "a"))*4)
length(unit(1:3, "npc") + unit(1, "strwidth", "a")*4)


Parallel Unit Minima and Maxima

Description

Returns a unit object whose i'th value is the minimum (or maximum) of the i'th values of the arguments.

Usage

unit.pmin(...)
unit.pmax(...)

Arguments

... One or more unit objects.

Details

The length of the result is the maximum of the lengths of the arguments; shorter arguments are recycled in the usual manner.

Value

A unit object.

Author(s)

Paul Murrell

Examples

max(unit(1:3, "cm"), unit(0.5, "npc"))
unit.pmax(unit(1:3, "cm"), unit(0.5, "npc"))


Replicate Elements of Unit Objects

Description

Replicates the units according to the values given in times and length.out.

This function has been deprecated in favour of a unit method for the generic rep function.

Usage

unit.rep(x, ...)

Arguments

x | An object of class "unit".
... | arguments to be passed to rep such as times and length.out.

Value

An object of class "unit".

Author(s)

Paul Murrell

See Also

rep

Examples

rep(unit(1:3, "npc"), 3)
rep(unit(1:3, "npc"), 1:3)
rep(unit(1:3, "npc") + unit(1, "inches"), 3)
rep(max(unit(1:3, "npc") + unit(1, "inches")), 3)
rep(max(unit(1:3, "npc") + unit(1, "strwidth", "a"))*4, 3)
rep(unit(1:3, "npc") + unit(1, "strwidth", "a")*4, 3)


Customising grid grob Validation

Description

This generic hook function is called whenever a grid grob is created or edited via grob, gTree, grid.edit or editGrob. This provides an opportunity for customising the validation of a new class derived from grob (or gTree).

Usage

validDetails(x)

Arguments

x A grid grob.

Details

This function is called by grob, gTree, grid.edit and editGrob. A method should be written for classes derived from grob or gTree to validate the values of slots specific to the new class. (e.g., see grid:::validDetails.axis).

Note that the standard slots for grobs and gTrees are automatically validated (e.g., vp, gp slots for grobs and, in addition, children, and childrenvp slots for gTrees) so only slots specific to a new class need to be addressed.

Value

The function MUST return the validated grob.

Author(s)

Paul Murrell

See Also

grid.edit


Create a Grid Viewport

Description

These functions create viewports, which describe rectangular regions on a graphics device and define a number of coordinate systems within those regions.

Usage

viewport(x = unit(0.5, "npc"), y = unit(0.5, "npc"),
         width = unit(1, "npc"), height = unit(1, "npc"),
         default.units = "npc", just = "centre",
         gp = gpar(), clip = "inherit",
         xscale = c(0, 1), yscale = c(0, 1),
         angle = 0,
         layout = NULL,
         layout.pos.row = NULL, layout.pos.col = NULL,
         name = NULL)
vpList(...)
vpStack(...)
vpTree(parent, children)

Arguments

x | A numeric vector or unit object specifying x-location.
y | A numeric vector or unit object specifying y-location.
width | A numeric vector or unit object specifying width.
height | A numeric vector or unit object specifying height.
default.units | A string indicating the default units to use if x, y, width, or height are only given as numeric vectors.
just | A string or numeric vector specifying the justification of the viewport relative to its (x, y) location. If there are two values, the first value specifes horizontal justification and the second value specifies vertical justification. Possible string values are: "left", "right", "centre", "center", "bottom", and "top". For numeric values, 0 means left alignment and 1 means right alignment.
gp | An object of class gpar, typically the output from a call to the function gpar. This is basically a list of graphical parameter settings.
clip | One of "on", "inherit", or "off", indicating whether to clip to the extent of this viewport, inherit the clipping region from the parent viewport, or turn clipping off altogether. For back-compatibility, a logical value of TRUE corresponds to "on" and FALSE corresponds to "inherit".
xscale | A numeric vector of length two indicating the minimum and maximum on the x-scale.
yscale | A numeric vector of length two indicating the minimum and maximum on the y-scale.
angle | A numeric value indicating the angle of rotation of the viewport. Positive values indicate the amount of rotation, in degrees, anitclockwise from the positive x-axis.
layout | A Grid layout object which splits the viewport into subregions.
layout.pos.row | A numeric vector giving the rows occupied by this viewport in its parent's layout.
layout.pos.col | A numeric vector giving the columns occupied by this viewport in its parent's layout.
name | A character value to uniquely identify the viewport once it has been pushed onto the viewport tree.
... | Any number of grid viewport objects.
parent | A grid viewport object.
children | A vpList object.

Details

The location and size of a viewport are relative to the coordinate systems defined by the viewport's parent (either a graphical device or another viewport). The location and size can be specified in a very flexible way by specifying them with unit objects. When specifying the location of a viewport, specifying both layout.pos.row and layout.pos.col as NULL indicates that the viewport ignores its parent's layout and specifies its own location and size (via its locn). If only one of layout.pos.row and layout.pos.col is NULL, this means occupy ALL of the appropriate row(s)/column(s). For example, layout.pos.row = 1 and layout.pos.col = NULL means occupy all of row 1. Specifying non-NULL values for both layout.pos.row and layout.pos.col means occupy the intersection of the appropriate rows and columns. If a vector of length two is specified for layout.pos.row or layout.pos.col, this indicates a range of rows or columns to occupy. For example, layout.pos.row = c(1, 3) and layout.pos.col = c(2, 4) means occupy cells in the intersection of rows 1, 2, and 3, and columns, 2, 3, and 4.

Clipping obeys only the most recent viewport clip setting. For example, if you clip to viewport1, then clip to viewport2, the clipping region is determined wholly by viewport2, the size and shape of viewport1 is irrelevant (until viewport2 is popped of course).

If a viewport is rotated (because of its own angle setting or because it is within another viewport which is rotated) then the clip flag is ignored.

Viewport names need not be unique. When pushed, viewports sharing the same parent must have unique names, which means that if you push a viewport with the same name as an existing viewport, the existing viewport will be replaced in the viewport tree. A viewport name can be any string, but grid uses the reserved name "ROOT" for the top-level viewport. Also, when specifying a viewport name in downViewport and seekViewport, it is possible to provide a viewport path, which consists of several names concatenated using the separator (currently ::). Consequently, it is not advisable to use this separator in viewport names.

The viewports in a vpList are pushed in parallel. The viewports in a vpStack are pushed in series. When a vpTree is pushed, the parent is pushed first, then the children are pushed in parallel.

Value

An R object of class viewport.

Author(s)

Paul Murrell

See Also

Grid, pushViewport, popViewport, downViewport, seekViewport, upViewport, unit, grid.layout, grid.show.layout.

Examples

# Diagram of a sample viewport
grid.show.viewport(viewport(x=0.6, y=0.6,
                   w=unit(1, "inches"), h=unit(1, "inches")))
# Demonstrate viewport clipping
clip.demo <- function(i, j, clip1, clip2) {
  pushViewport(viewport(layout.pos.col=i,
                         layout.pos.row=j))
  pushViewport(viewport(width=0.6, height=0.6, clip=clip1))
  grid.rect(gp=gpar(fill="white"))
  grid.circle(r=0.55, gp=gpar(col="red", fill="pink"))
  popViewport()
  pushViewport(viewport(width=0.6, height=0.6, clip=clip2))
  grid.polygon(x=c(0.5, 1.1, 0.6, 1.1, 0.5, -0.1, 0.4, -0.1),
               y=c(0.6, 1.1, 0.5, -0.1, 0.4, -0.1, 0.5, 1.1),
               gp=gpar(col="blue", fill="light blue"))
  popViewport(2)
}

grid.newpage()
grid.rect(gp=gpar(fill="grey"))
pushViewport(viewport(layout=grid.layout(2, 2)))
clip.demo(1, 1, FALSE, FALSE)
clip.demo(1, 2, TRUE, FALSE)
clip.demo(2, 1, FALSE, TRUE)
clip.demo(2, 2, TRUE, TRUE)
popViewport()
# Demonstrate turning clipping off
grid.newpage()
pushViewport(viewport(w=.5, h=.5, clip="on"))
grid.rect()
grid.circle(r=.6, gp=gpar(lwd=10))
pushViewport(viewport(clip="inherit"))
grid.circle(r=.6, gp=gpar(lwd=5, col="grey"))
pushViewport(viewport(clip="off"))
grid.circle(r=.6)
popViewport(3)
# Demonstrate vpList, vpStack, and vpTree
grid.newpage()
tree <- vpTree(viewport(w=0.8, h=0.8, name="A"),
               vpList(vpStack(viewport(x=0.1, y=0.1, w=0.5, h=0.5,
                                       just=c("left", "bottom"), name="B"),
                              viewport(x=0.1, y=0.1, w=0.5, h=0.5,
                                       just=c("left", "bottom"), name="C"),
                              viewport(x=0.1, y=0.1, w=0.5, h=0.5,
                                       just=c("left", "bottom"), name="D")),
                      viewport(x=0.5, w=0.4, h=0.9,
                               just="left", name="E")))
pushViewport(tree)
for (i in LETTERS[1:5]) {
  seekViewport(i)
  grid.rect()
  grid.text(current.vpTree(FALSE),
            x=unit(1, "mm"), y=unit(1, "npc") - unit(1, "mm"),
            just=c("left", "top"),
            gp=gpar(fontsize=8))
}


Maintaining and Navigating the Grid Viewport Tree

Description

Grid maintains a tree of viewports — nested drawing contexts.

These functions provide ways to add or remove viewports and to navigate amongst viewports in the tree.

Usage

pushViewport(..., recording=TRUE)
popViewport(n, recording=TRUE)
downViewport(name, strict=FALSE, recording=TRUE)
seekViewport(name, recording=TRUE)
upViewport(n, recording=TRUE)

Arguments

... | One or more objects of class "viewport".
n | An integer value indicating how many viewports to pop or navigate up. The special value 0 indicates to pop or navigate viewports right up to the root viewport.
name | A character value to identify a viewport in the tree.
strict | A boolean indicating whether the vpPath must be matched exactly.
recording | A logical value to indicate whether the viewport operation should be recorded on the Grid display list.

Details

Objects created by the viewport() function are only descriptions of a drawing context. A viewport object must be pushed onto the viewport tree before it has any effect on drawing.

The viewport tree always has a single root viewport (created by the system) which corresponds to the entire device (and default graphical parameter settings). Viewports may be added to the tree using pushViewport() and removed from the tree using popViewport().

There is only ever one current viewport, which is the current position within the viewport tree. All drawing and viewport operations are relative to the current viewport. When a viewport is pushed it becomes the current viewport. When a viewport is popped, the parent viewport becomes the current viewport. Use upViewport to navigate to the parent of the current viewport, without removing the current viewport from the viewport tree. Use downViewport to navigate to a viewport further down the viewport tree and seekViewport to navigate to a viewport anywhere else in the tree.

If a viewport is pushed and it has the same name as a viewport at the same level in the tree, then it replaces the existing viewport in the tree.

Value

downViewport returns the number of viewports it went down.
This can be useful for returning to your starting point by doing something like depth <- downViewport() then upViewport(depth).

Author(s)

Paul Murrell

See Also

viewport and vpPath.

Examples

# push the same viewport several times
grid.newpage()
vp <- viewport(width=0.5, height=0.5)
pushViewport(vp)
grid.rect(gp=gpar(col="blue"))
grid.text("Quarter of the device",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="blue"))
pushViewport(vp)
grid.rect(gp=gpar(col="red"))
grid.text("Quarter of the parent viewport",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="red"))
popViewport(2)
# push several viewports then navigate amongst them
grid.newpage()
grid.rect(gp=gpar(col="grey"))
grid.text("Top-level viewport",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="grey"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(width=0.8, height=0.7, name="A"))
grid.rect(gp=gpar(col="blue"))
grid.text("1. Push Viewport A",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(x=0.1, width=0.3, height=0.6,
  just="left", name="B"))
grid.rect(gp=gpar(col="red"))
grid.text("2. Push Viewport B (in A)",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="red"))
if (interactive()) Sys.sleep(1.0)
upViewport(1)
grid.text("3. Up from B to A",
  y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(x=0.5, width=0.4, height=0.8,
  just="left", name="C"))
grid.rect(gp=gpar(col="green"))
grid.text("4. Push Viewport C (in A)",
  y=unit(1, "npc") - unit(1, "lines"), gp=gpar(col="green"))
if (interactive()) Sys.sleep(1.0)
pushViewport(viewport(width=0.8, height=0.6, name="D"))
grid.rect()
grid.text("5. Push Viewport D (in C)",
  y=unit(1, "npc") - unit(1, "lines"))
if (interactive()) Sys.sleep(1.0)
upViewport(0)
grid.text("6. Up from D to top-level",
  y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="grey"))
if (interactive()) Sys.sleep(1.0)
downViewport("D")
grid.text("7. Down from top-level to D",
  y=unit(1, "npc") - unit(2, "lines"))
if (interactive()) Sys.sleep(1.0)
seekViewport("B")
grid.text("8. Seek from D to B",
  y=unit(1, "npc") - unit(2, "lines"), gp=gpar(col="red"))
pushViewport(viewport(width=0.9, height=0.5, name="A"))
grid.rect()
grid.text("9. Push Viewport A (in B)",
  y=unit(1, "npc") - unit(1, "lines"))
if (interactive()) Sys.sleep(1.0)
seekViewport("A")
grid.text("10. Seek from B to A (in ROOT)",
  y=unit(1, "npc") - unit(3, "lines"), gp=gpar(col="blue"))
if (interactive()) Sys.sleep(1.0)
seekViewport(vpPath("B", "A"))
grid.text("11. Seek from\nA (in ROOT)\nto A (in B)")
popViewport(0)


Concatenate Viewport Names

Description

This function can be used to generate a viewport path for use in downViewport or seekViewport.

A viewport path is a list of nested viewport names.

Usage

vpPath(...)

Arguments

... Character values which are viewport names.

Details

Viewport names must only be unique amongst viewports which share the same parent in the viewport tree.

This function can be used to generate a specification for a viewport that includes the viewport's parent's name (and the name of its parent and so on).

For interactive use, it is possible to directly specify a path, but it is strongly recommended that this function is used otherwise in case the path separator is changed in future versions of grid.

Value

A vpPath object.

See Also

viewport, pushViewport, popViewport, downViewport, seekViewport, upViewport

Examples

vpPath("vp1", "vp2")


Width and Height of a grid grob

Description

These generic functions are used to determine the size of grid grobs.

Usage

widthDetails(x)
heightDetails(x)

Arguments

x A grid grob.

Details

These functions are called in the calculation of "grobwidth" and "grobheight" units. Methods should be written for classes derived from grob or gTree where the size of the grob can be determined (see, for example grid:::widthDetails.frame).

Value

A unit object.

Author(s)

Paul Murrell

See Also

absolute.size.


Boundary of a grid grob

Description

These generic functions are used to determine a location on the boundary of a grid grob.

Usage

xDetails(x, theta)
yDetails(x, theta)

Arguments

x | A grid grob.
theta | A numeric angle, in degrees, measured anti-clockwise from the 3 o'clock or one of the following character strings: "north", "east", "west", "south".

Details

The location on the grob boundary is determined by taking a line from the centre of the grob at the angle theta and intersecting it with the convex hull of the grob (for the basic grob primitives, the centre is determined as half way between the minimum and maximum values in x and y directions).

These functions are called in the calculation of "grobx" and "groby" units as produced by the grobX and grobY functions. Methods should be written for classes derived from grob or gTree where the boundary of the grob can be determined.

Value

A unit object.

Author(s)

Paul Murrell

See Also

grobX, grobY.