Title: | Trellis Graphics for R |
---|---|
Description: | A powerful and elegant high-level data visualization system inspired by Trellis graphics, with an emphasis on multivariate data. Lattice is sufficient for typical graphics needs, and is also flexible enough to handle most nonstandard requirements. See ?Lattice for an introduction. |
Authors: | Deepayan Sarkar [aut, cre] , Felix Andrews [ctb], Kevin Wright [ctb] (documentation), Neil Klepeis [ctb], Johan Larsson [ctb] (miscellaneous improvements), Zhijian (Jason) Wen [cph] (filled contour code), Paul Murrell [ctb], Stefan Eng [ctb] (violin plot improvements), Achim Zeileis [ctb] (modern colors), Alexandre Courtiol [ctb] (generics for larrows, lpolygon, lrect and lsegments) |
Maintainer: | Deepayan Sarkar <[email protected]> |
License: | GPL (>= 2) |
Version: | 0.22-5 |
Built: | 2024-11-04 05:50:14 UTC |
Source: | https://github.com/deepayan/lattice |
The lattice add-on package is an implementation of Trellis graphics for R. It is a powerful and elegant high-level data visualization system with an emphasis on multivariate data. It is designed to meet most typical graphics needs with minimal tuning, but can also be easily extended to handle most nonstandard requirements.
Trellis Graphics, originally developed for S and S-PLUS at the Bell Labs, is a framework for data visualization developed by R. A. Becker, W. S. Cleveland, et al, extending ideas presented in Cleveland's 1993 book Visualizing Data. The Lattice API is based on the original design in S, but extends it in many ways.
The Lattice user interface primarily consists of several
‘high-level’ generic functions (listed below in the “See
Also” section), each designed to create a particular type of display
by default. Although the functions produce different output, they
share many common features, reflected in several common arguments that
affect the resulting displays in similar ways. These arguments are
extensively (sometimes only) documented in the help page for
xyplot
, which also includes a discussion of the
important topics of conditioning and control of the Trellis
layout. Features specific to other high-level functions are
documented in their respective help pages.
Lattice employs an extensive system of user-controllable settings to
determine the look and feel of the displays it produces. To learn how
to use and customize the graphical parameters used by lattice, see
trellis.par.set
. For other settings, see
lattice.options
. The default graphical settings are
(potentially) different for different graphical devices. To learn how
to initialize new devices with the desired settings or change the
settings of the current device, see trellis.device
.
It is usually unnecessary, but sometimes important to be able to plot
multiple lattice plots on a single page. Such capabilities are
described in the print.trellis
help page. See
update.trellis
to learn about manipulating a
"trellis"
object. Tools to augment lattice plots after they
are drawn (including locator
-like functionality) are
described in the trellis.focus
help page.
The online documentation accompanying the package is complete, and effort has been made to present the help pages in a logical sequence, so that one can learn how to use lattice by reading the PDF reference manual available at https://cran.r-project.org/package=lattice. However, the format in which the online documentation is written and the breadth of topics covered necessarily makes it somewhat terse and less than ideal as a first introduction. For a more gentle introduction, a book on lattice is available as part of Springer's ‘Use R’ series; see the “References” section below.
High-level lattice functions like xyplot
are
different from traditional R graphics functions in that they do not
perform any plotting themselves. Instead, they return an object, of
class "trellis"
, which has to be then
print
-ed or
plot
-ted to create the actual
plot. Due to R's automatic printing rule, it is usually not
necessary to explicitly carry out the second step, and lattice
functions appear to behave like their traditional counterparts.
However, the automatic plotting is suppressed when the high-level
functions are called inside another function (most often
source
) or in other contexts where automatic printing is
suppressed (e.g., for
or while
loops). In
such situations, an explicit call to print
or plot
is
required.
The lattice package is based on the Grid graphics engine and
requires the grid add-on package. One consquence of this is
that it is not (readily) compatible with traditional R graphics
tools. In particular, changing par()
settings usually has no
effect on Lattice plots; lattice provides its own interface for
querying and modifying an extensive set of graphical and non-graphical
settings.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. ISBN: 978-0-387-75968-5 http://lmdvr.r-forge.r-project.org/
Cleveland, William .S. (1993) Visualizing Data, Hobart Press, Summit, New Jersey.
Becker, R. A. and Cleveland, W. S. and Shyu, M. J. (1996). “The Visual Design and Control of Trellis Display”, Journal of Computational and Graphical Statistics, 5(2), 123–155.
Bell Lab's Trellis Page contains several documents outlining the use of Trellis graphics; these provide a holistic introduction to the Trellis paradigm: http://web.archive.org/web/20081020164041/http://cm.bell-labs.com/cm/ms/departments/sia/project/trellis/display.writing.html
The following is a list of high-level functions in the lattice
package and their default displays. In all cases, the actual display
is produced by the so-called “panel” function, which has a
suitable default, but can be substituted by an user defined function
to create customized displays. In many cases, the default panel
function will itself have many optional arguments to customize its
output. The default panel functions are named as
“panel.
” followed by the name of the corresponding
high-level function; i.e., the default panel function for
xyplot
is panel.xyplot
, the one for
histogram
is panel.histogram
, etc. Each
default panel function has a separate help page, linked from the help
pages of the corresponding high-level function. Although documented
separately, arguments to these panel functions can be supplied
directly to the high-level functions, which will pass on the arguments
appropriately.
Univariate:
barchart
:Bar plots.
bwplot
:Box-and-whisker plots.
densityplot
:Kernel density estimates.
dotplot
:Cleveland dot plots.
histogram
:Histograms.
qqmath
:Theretical quantile plots.
stripplot
:One-dimensional scatterplots.
Bivariate:
qq
:Quantile plots for comparing two distributions.
xyplot
:Scatterplots and time-series plots (and potentially a lot more).
Trivariate:
levelplot
: Level plots (similar to image
plots).
contourplot
:Contour plots.
cloud
:Three-dimensional scatter plots.
wireframe
: Three-dimensional surface plots (similar to persp
plots).
Hypervariate:
Miscellaneous:
In addition, there are several panel functions that do little by
themselves, but can be useful components of custom panel functions.
These are documented in panel.functions
. Lattice also
provides a collection of convenience functions that correspond to the
traditional graphics primitives lines
,
points
, etc. These are implemented using Grid graphics,
but try to be as close to the traditional versions as possible in
terms of their argument list. These functions have names like
llines
or panel.lines
and are often useful
when writing (or porting from S-PLUS code) nontrivial panel functions.
Finally, many useful enhancements that extend the Lattice system are available in the latticeExtra package.
## Not run: ## Show brief history of changes to lattice, including ## a summary of new features. RShowDoc("NEWS", package = "lattice") ## End(Not run)
## Not run: ## Show brief history of changes to lattice, including ## a summary of new features. RShowDoc("NEWS", package = "lattice") ## End(Not run)
This help page documents several commonly used high-level Lattice
functions. xyplot
produces bivariate scatterplots or
time-series plots, bwplot
produces box-and-whisker plots,
dotplot
produces Cleveland dot plots, barchart
produces
bar plots, and stripplot
produces one-dimensional scatterplots.
All these functions, along with other high-level Lattice functions,
respond to a common set of arguments that control conditioning,
layout, aspect ratio, legends, axis annotation, and many other details
in a consistent manner. These arguments are described extensively in
this help page, and should be used as the reference for other
high-level functions as well.
For control and customization of the actual display in each panel, the help page of the respective default panel function will often be more informative. In particular, these help pages describe many arguments commonly used when calling the corresponding high-level function but are specific to them.
xyplot(x, data, ...) dotplot(x, data, ...) barchart(x, data, ...) stripplot(x, data, ...) bwplot(x, data, ...) ## S3 method for class 'formula' xyplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.xyplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.xyplot"), subscripts = !is.null(groups), subset = TRUE) ## S3 method for class 'data.frame' xyplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' dotplot(x, data, panel = lattice.getOption("panel.dotplot"), default.prepanel = lattice.getOption("prepanel.default.dotplot"), ...) ## S3 method for class 'data.frame' dotplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' barchart(x, data, panel = lattice.getOption("panel.barchart"), default.prepanel = lattice.getOption("prepanel.default.barchart"), box.ratio = 2, ...) ## S3 method for class 'data.frame' barchart(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' stripplot(x, data, panel = lattice.getOption("panel.stripplot"), default.prepanel = lattice.getOption("prepanel.default.stripplot"), ...) ## S3 method for class 'data.frame' stripplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' bwplot(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.bwplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, box.ratio = 1, horizontal = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.bwplot"), subscripts = !is.null(groups), subset = TRUE) ## S3 method for class 'data.frame' bwplot(x, data = NULL, formula = data, ...)
xyplot(x, data, ...) dotplot(x, data, ...) barchart(x, data, ...) stripplot(x, data, ...) bwplot(x, data, ...) ## S3 method for class 'formula' xyplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.xyplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.xyplot"), subscripts = !is.null(groups), subset = TRUE) ## S3 method for class 'data.frame' xyplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' dotplot(x, data, panel = lattice.getOption("panel.dotplot"), default.prepanel = lattice.getOption("prepanel.default.dotplot"), ...) ## S3 method for class 'data.frame' dotplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' barchart(x, data, panel = lattice.getOption("panel.barchart"), default.prepanel = lattice.getOption("prepanel.default.barchart"), box.ratio = 2, ...) ## S3 method for class 'data.frame' barchart(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' stripplot(x, data, panel = lattice.getOption("panel.stripplot"), default.prepanel = lattice.getOption("prepanel.default.stripplot"), ...) ## S3 method for class 'data.frame' stripplot(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' bwplot(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.bwplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, box.ratio = 1, horizontal = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.bwplot"), subscripts = !is.null(groups), subset = TRUE) ## S3 method for class 'data.frame' bwplot(x, data = NULL, formula = data, ...)
x |
All high-level function in lattice are generic. For the For the functions documented here, the formula is generally of the
form With the exception of Cases where The conditioning variables Extended formula interface: As a useful extension of the
interface described above, the primary variable terms (both the LHS
To interpret A variation on this feature is when the Primary variables: The Note that the |
data |
For the |
formula |
The formula to be used for the |
allow.multiple |
Logical flag specifying whether the extended formula interface
described above should be in effect. Defaults to |
outer |
Logical flag controlling what happens with formulas using the
extended interface described above (see the entry for |
box.ratio |
Applicable to |
horizontal |
Logical flag applicable to A potentially useful component of |
Common arguments: The following arguments are common to all the functions documented here, as well as most other high-level Trellis functions. These are not documented elsewhere, except to override the usage given here.
panel |
Once the subset of rows defined by each unique combination of the
levels of the grouping variables are obtained (see
“Details”), the corresponding Much of the power of Trellis Graphics comes from the ability to
define customized panel functions. A panel function appropriate for
the functions described here would usually expect arguments named
Note that unlike in S-PLUS, it is not guaranteed that panel
functions will be supplied only numeric vectors for the Technically speaking, panel functions must be written using Grid
graphics functions. However, knowledge of Grid is usually not
necessary to construct new custom panel functions, as there are
several predefined panel functions which can help; for example,
One case where a bit more is required of the panel function is when
the Even when This interpretation of One can also use functions called
|
aspect |
This argument controls the physical aspect ratio of the panels,
which is usually the same for all the panels. It can be specified as
a ratio (vertical size/horizontal size) or as a character string.
In the latter case, legitimate values are If a |
groups |
A variable or expression to be evaluated in It is very common to use a key (legend) when a grouping variable is
specified. See entries for |
auto.key |
A logical, or a list containing components to be used as arguments
to
More precisely, if Note that One disadvantage to using |
prepanel |
A function that takes the same arguments as the The The If In such cases, an additional component The prepanel function is responsible for providing a meaningful
return value when the |
strip |
A logical flag or function. If |
xlab |
Character or expression (or a |
ylab |
Character or expression (or |
scales |
Generally a list determining how the x- and y-axes (tick marks and
labels) are drawn. The list contains parameters in
As a special exception, The possible components are :
Note that much of the function of |
subscripts |
A logical flag specifying whether or not a vector named
|
subset |
An expression that evaluates to a logical or integer indexing
vector. Like |
xlim |
Normally a numeric vector (or a DateTime object) of length 2 giving
left and right limits for the x-axis, or a character vector,
expected to denote the levels of
|
ylim |
Similar to |
drop.unused.levels |
A logical flag indicating whether the unused levels of factors will
be dropped, usually relevant when a subsetting operation is
performed or an |
default.scales |
A list giving the default values of |
default.prepanel |
A function or character string giving the name of a function that
serves as the (component-wise) fallback prepanel function when the
|
lattice.options |
A list that could be supplied to |
... |
Further arguments, usually not directly processed by the high-level functions documented here, but instead passed on to other functions. Such arguments can be broadly categorized into two types: those that affect all high-level Lattice functions in a similar manner, and those that are meant for the specific panel function being used. The first group of arguments are processed by a common, unexported
function called The effect of the first group of common arguments are as follows:
|
The high-level functions documented here, as well as other high-level
Lattice functions, are generic, with the formula
method usually
doing the most substantial work. The structure of the plot that is
produced is mostly controlled by the formula (implicitly in the case
of the non-formula methods). For each unique combination of the
levels of the conditioning variables g1, g2, ...
, a separate
“packet” is produced, consisting of the points (x,y)
for
the subset of the data defined by that combination. The display can
be thought of as a three-dimensional array of panels, consisting of one
two-dimensional matrix per page. The dimensions of this array are
determined by the layout
argument. If there are no
conditioning variables, the plot produced consists of a single packet.
Each packet usually corresponds to one panel, but this is not strictly
necessary (see the entry for index.cond
above).
The coordinate system used by lattice by default is like a
graph, with the origin at the bottom left, with axes increasing to the
right and top. In particular, panels are by default drawn starting
from the bottom left corner, going right and then up, unless
as.table = TRUE
, in which case panels are drawn from the top
left corner, going right and then down. It is possible to set a
global preference for the table-like arrangement by changing the
default to as.table=TRUE
; this can be done by setting
lattice.options(default.args = list(as.table = TRUE))
. Default
values can be set in this manner for the following arguments:
as.table
, aspect
, between
, page
,
main
, sub
, par.strip.text
, layout
,
skip
and strip
. Note that these global defaults are
sometimes overridden by individual functions.
The order of the panels depends on the order in which the conditioning
variables are specified, with g1
varying fastest, followed by
g2
, and so on. Within a conditioning variable, the order
depends on the order of the levels (which for factors is usually in
alphabetical order). Both of these orders can be modified using the
index.cond
and perm.cond
arguments, possibly using the
update
(and other related)
method(s).
The high-level functions documented here, as well as other high-level
Lattice functions, return an object of class "trellis"
. The
update
method can be used to
subsequently update components of the object, and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Most of the arguments documented here are also applicable for the other high-level functions in the lattice package. These are not described in any detail elsewhere unless relevant, and this should be considered the canonical documentation for such arguments.
Any arguments passed to these functions and not recognized by them will be passed to the panel function. Most predefined panel functions have arguments that customize its output. These arguments are described only in the help pages for these panel functions, but can usually be supplied as arguments to the high-level plot.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
Lattice
for an overview of the package, as well as
barchart.table
,
print.trellis
,
shingle
,
banking
,
reshape
,
panel.xyplot
,
panel.bwplot
,
panel.barchart
,
panel.dotplot
,
panel.stripplot
,
panel.superpose
,
panel.loess
,
panel.average
,
strip.default
,
simpleKey
trellis.par.set
require(stats) ## Tonga Trench Earthquakes Depth <- equal.count(quakes$depth, number=8, overlap=.1) xyplot(lat ~ long | Depth, data = quakes) update(trellis.last.object(), strip = strip.custom(strip.names = TRUE, strip.levels = TRUE), par.strip.text = list(cex = 0.75), aspect = "iso") ## Extended formula interface xyplot(Sepal.Length + Sepal.Width ~ Petal.Length + Petal.Width | Species, data = iris, scales = "free", layout = c(2, 2), auto.key = list(x = .75, y = .75, corner = c(0.5, 0.5))) ## user defined panel functions states <- data.frame(state.x77, state.name = dimnames(state.x77)[[1]], state.region = state.region) xyplot(Murder ~ Population | state.region, data = states, snames = states$state.name, panel = function(x, y, subscripts, snames) { panel.text(x = x, y = y, labels = snames[subscripts], cex = 1, fontfamily = "HersheySans") }) ## Stacked bar chart barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), stack = TRUE, auto.key = list(space = "right"), ylab = "Barley Yield (bushels/acre)", scales = list(x = list(rot = 45))) bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)") dotplot(variety ~ yield | year * site, data=barley) ## Grouped dot plot showing anomaly at Morris dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL) stripplot(voice.part ~ jitter(height), data = singer, aspect = 1, jitter.data = TRUE, xlab = "Height (inches)") ## Interaction Plot xyplot(decrease ~ treatment, OrchardSprays, groups = rowpos, type = "a", auto.key = list(space = "right", points = FALSE, lines = TRUE)) ## longer version with no x-ticks ## Not run: bwplot(decrease ~ treatment, OrchardSprays, groups = rowpos, panel = "panel.superpose", panel.groups = "panel.linejoin", xlab = "treatment", key = list(lines = Rows(trellis.par.get("superpose.line"), c(1:7, 1)), text = list(lab = as.character(unique(OrchardSprays$rowpos))), columns = 4, title = "Row position")) ## End(Not run)
require(stats) ## Tonga Trench Earthquakes Depth <- equal.count(quakes$depth, number=8, overlap=.1) xyplot(lat ~ long | Depth, data = quakes) update(trellis.last.object(), strip = strip.custom(strip.names = TRUE, strip.levels = TRUE), par.strip.text = list(cex = 0.75), aspect = "iso") ## Extended formula interface xyplot(Sepal.Length + Sepal.Width ~ Petal.Length + Petal.Width | Species, data = iris, scales = "free", layout = c(2, 2), auto.key = list(x = .75, y = .75, corner = c(0.5, 0.5))) ## user defined panel functions states <- data.frame(state.x77, state.name = dimnames(state.x77)[[1]], state.region = state.region) xyplot(Murder ~ Population | state.region, data = states, snames = states$state.name, panel = function(x, y, subscripts, snames) { panel.text(x = x, y = y, labels = snames[subscripts], cex = 1, fontfamily = "HersheySans") }) ## Stacked bar chart barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), stack = TRUE, auto.key = list(space = "right"), ylab = "Barley Yield (bushels/acre)", scales = list(x = list(rot = 45))) bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)") dotplot(variety ~ yield | year * site, data=barley) ## Grouped dot plot showing anomaly at Morris dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL) stripplot(voice.part ~ jitter(height), data = singer, aspect = 1, jitter.data = TRUE, xlab = "Height (inches)") ## Interaction Plot xyplot(decrease ~ treatment, OrchardSprays, groups = rowpos, type = "a", auto.key = list(space = "right", points = FALSE, lines = TRUE)) ## longer version with no x-ticks ## Not run: bwplot(decrease ~ treatment, OrchardSprays, groups = rowpos, panel = "panel.superpose", panel.groups = "panel.linejoin", xlab = "treatment", key = list(lines = Rows(trellis.par.get("superpose.line"), c(1:7, 1)), text = list(lab = as.character(unique(OrchardSprays$rowpos))), columns = 4, title = "Row position")) ## End(Not run)
This function handles time series plotting, including cut-and-stack plots. Examples are given of superposing, juxtaposing and styling different time series.
## S3 method for class 'ts' xyplot(x, data = NULL, screens = if (superpose) 1 else colnames(x), ..., superpose = FALSE, cut = FALSE, type = "l", col = NULL, lty = NULL, lwd = NULL, pch = NULL, cex = NULL, fill = NULL, auto.key = superpose, panel = if (superpose) "panel.superpose" else "panel.superpose.plain", par.settings = list(), layout = NULL, as.table = TRUE, xlab = "Time", ylab = NULL, default.scales = list(y = list(relation = if (missing(cut)) "free" else "same")))
## S3 method for class 'ts' xyplot(x, data = NULL, screens = if (superpose) 1 else colnames(x), ..., superpose = FALSE, cut = FALSE, type = "l", col = NULL, lty = NULL, lwd = NULL, pch = NULL, cex = NULL, fill = NULL, auto.key = superpose, panel = if (superpose) "panel.superpose" else "panel.superpose.plain", par.settings = list(), layout = NULL, as.table = TRUE, xlab = "Time", ylab = NULL, default.scales = list(y = list(relation = if (missing(cut)) "free" else "same")))
x |
an object of class |
data |
not used, and must be left as |
... |
additional arguments passed to |
screens |
factor (or coerced to factor) whose levels specify which
panel each series is to be plotted in. |
superpose |
overlays all series in one panel (via |
cut |
defines a cut-and-stack plot.
|
type , col , lty , lwd , pch , cex , fill
|
graphical arguments, which are processed and eventually passed to
|
auto.key |
a logical, or a list describing how to draw a key. See the
|
panel |
the panel function. It is recommended to leave this alone, but one
can pass a |
par.settings |
style settings beyond the standard |
layout |
numeric vector of length 2 specifying number of columns and rows in the plot. The default is to fill columns with up to 6 rows. |
as.table |
to draw panels from top to bottom. The order is determined by the
order of columns in |
xlab , ylab
|
X axis and Y axis labels; see |
default.scales |
|
The handling of several graphical parameters is more
flexible for multivariate series. These parameters can be
vectors of the same length as the number of series plotted or
are recycled if shorter. They can also be (partially) named list, e.g.,
list(A = c(1,2), c(3,4))
in which c(3, 4)
is the
default value and c(1, 2)
the value only for series A
.
The screens
argument can be specified in a similar way.
Some examples are given below.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Gabor Grothendieck, Achim Zeileis, Deepayan Sarkar and Felix Andrews [email protected].
The first two authors developed xyplot.ts
in their zoo
package, including the screens
approach. The third author
developed a different xyplot.ts
for cut-and-stack plots in the
latticeExtra package. The final author fused these together.
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/ (cut-and-stack plots)
xyplot
,
panel.xyplot
,
plot.ts
,
ts
,
xyplot.zoo
in the zoo package.
xyplot(ts(c(1:10,10:1))) ### Figure 14.1 from Sarkar (2008) xyplot(sunspot.year, aspect = "xy", strip = FALSE, strip.left = TRUE, cut = list(number = 4, overlap = 0.05)) ### A multivariate example; first juxtaposed, then superposed xyplot(EuStockMarkets, scales = list(y = "same")) xyplot(EuStockMarkets, superpose = TRUE, aspect = "xy", lwd = 2, type = c("l","g"), ylim = c(0, max(EuStockMarkets))) ### Examples using screens (these two are identical) xyplot(EuStockMarkets, screens = c(rep("Continental", 3), "UK")) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental")) ### Automatic group styles xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE, xlim = extendrange(1996:1998), par.settings = standard.theme(color = FALSE)) ### Specifying styles for series by name xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red", FTSE = "blue", "black"), auto.key = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red"), lty = list(SMI = 2), lwd = 1:2, auto.key = TRUE) ### Example with simpler data, few data points set.seed(1) z <- ts(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) xyplot(z, screens = 1) xyplot(z, screens = list(a = "primary (a)", "other (b & c)"), type = list(a = c("p", "h"), b = c("p", "s"), "o"), pch = list(a = 2, c = 3), auto.key = list(type = "o"))
xyplot(ts(c(1:10,10:1))) ### Figure 14.1 from Sarkar (2008) xyplot(sunspot.year, aspect = "xy", strip = FALSE, strip.left = TRUE, cut = list(number = 4, overlap = 0.05)) ### A multivariate example; first juxtaposed, then superposed xyplot(EuStockMarkets, scales = list(y = "same")) xyplot(EuStockMarkets, superpose = TRUE, aspect = "xy", lwd = 2, type = c("l","g"), ylim = c(0, max(EuStockMarkets))) ### Examples using screens (these two are identical) xyplot(EuStockMarkets, screens = c(rep("Continental", 3), "UK")) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental")) ### Automatic group styles xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE, xlim = extendrange(1996:1998), par.settings = standard.theme(color = FALSE)) ### Specifying styles for series by name xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red", FTSE = "blue", "black"), auto.key = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red"), lty = list(SMI = 2), lwd = 1:2, auto.key = TRUE) ### Example with simpler data, few data points set.seed(1) z <- ts(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) xyplot(z, screens = 1) xyplot(z, screens = list(a = "primary (a)", "other (b & c)"), type = list(a = c("p", "h"), b = c("p", "s"), "o"), pch = list(a = 2, c = 3), auto.key = list(type = "o"))
Contingency tables are often displayed using bar charts and dot plots. These methods operate directly on tables, bypassing the need to convert them to data frames for use with the formula interface. Matrices and arrays are also supported, by coercing them to tables.
## S3 method for class 'table' barchart(x, data, groups = TRUE, origin = 0, stack = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' barchart(x, data, ...) ## S3 method for class 'matrix' barchart(x, data, ...) ## S3 method for class 'table' dotplot(x, data, groups = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' dotplot(x, data, ...) ## S3 method for class 'matrix' dotplot(x, data, ...)
## S3 method for class 'table' barchart(x, data, groups = TRUE, origin = 0, stack = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' barchart(x, data, ...) ## S3 method for class 'matrix' barchart(x, data, ...) ## S3 method for class 'table' dotplot(x, data, groups = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' dotplot(x, data, ...) ## S3 method for class 'matrix' dotplot(x, data, ...)
x |
A |
data |
Should not be specified. If specified, will be ignored with a warning. |
groups |
A logical flag, indicating whether to use the last dimension as a grouping variable in the display. |
origin , stack
|
Arguments to |
horizontal |
Logical flag, indicating whether the plot should be horizontal (with the categorical variable on the y-axis) or vertical. |
... |
Other arguments, passed to the underlying |
The first dimension is used as the variable on the categorical axis.
The last dimension is optionally used as a grouping variable (to
produce stacked barcharts by default). All other dimensions are used
as conditioning variables. The order of these variables cannot be
altered (except by permuting the original argument beforehand using
t
or aperm
). For more flexibility, use
the formula method after converting the table to a data frame using
the relevant as.data.frame
method.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
barchart
, t
, aperm
,
table
, panel.barchart
,
Lattice
barchart(Titanic, scales = list(x = "free"), auto.key = list(title = "Survived"))
barchart(Titanic, scales = list(x = "free"), auto.key = list(title = "Survived"))
Draw Histograms and Kernel Density Plots, possibly conditioned on other variables.
histogram(x, data, ...) densityplot(x, data, ...) ## S3 method for class 'formula' histogram(x, data, allow.multiple, outer = TRUE, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.histogram"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, type = c("percent", "count", "density"), nint = if (is.factor(x)) nlevels(x) else round(log2(length(x)) + 1), endpoints = extend.limits(range(as.numeric(x), finite = TRUE), prop = 0.04), breaks, equal.widths = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.histogram"), subscripts, subset) ## S3 method for class 'data.frame' histogram(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'factor' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'formula' densityplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.densityplot"), prepanel, scales, strip, groups, weights, xlab, xlim, ylab, ylim, bw, adjust, kernel, window, width, give.Rkern, n = 512, from, to, cut, na.rm, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.densityplot"), subscripts, subset) ## S3 method for class 'data.frame' densityplot(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' densityplot(x, data = NULL, xlab, ...) do.breaks(endpoints, nint)
histogram(x, data, ...) densityplot(x, data, ...) ## S3 method for class 'formula' histogram(x, data, allow.multiple, outer = TRUE, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.histogram"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, type = c("percent", "count", "density"), nint = if (is.factor(x)) nlevels(x) else round(log2(length(x)) + 1), endpoints = extend.limits(range(as.numeric(x), finite = TRUE), prop = 0.04), breaks, equal.widths = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.histogram"), subscripts, subset) ## S3 method for class 'data.frame' histogram(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'factor' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'formula' densityplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.densityplot"), prepanel, scales, strip, groups, weights, xlab, xlim, ylab, ylim, bw, adjust, kernel, window, width, give.Rkern, n = 512, from, to, cut, na.rm, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.densityplot"), subscripts, subset) ## S3 method for class 'data.frame' densityplot(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' densityplot(x, data = NULL, xlab, ...) do.breaks(endpoints, nint)
x |
The object on which method dispatch is carried out. For the As a special case, the right hand side of the formula can contain
more than one term separated by ‘+’ signs (e.g., For the |
data |
For the |
formula |
The formula to be used for the |
type |
A character string indicating the type of histogram that is to be
drawn.
|
nint |
An integer specifying the number of histogram bins, applicable only
when |
endpoints |
A numeric vector of length 2 indicating the range of x-values that
is to be covered by the histogram. This applies only when
|
breaks |
Usually a numeric vector of length (number of bins + 1) defining the
breakpoints of the bins. Note that when breakpoints are not equally
spaced, the only value of When breaks = seq_len(1 + nlevels(x)) - 0.5 when breaks = do.breaks(endpoints, nint) otherwise. Breakpoints calculated in such a manner are used in all
panels. If the retrieved value is not When specified explicitly, a special value of |
equal.widths |
A logical flag, relevant only when |
n |
Integer, giving the number of points at which the kernel density is
to be evaluated. Passed on as an argument to |
panel |
A function, called once for each panel, that uses the packet (subset
of panel variables) corresponding to the panel to create a display.
The default panel functions |
allow.multiple , outer
|
See |
auto.key |
See |
aspect |
See |
prepanel |
See |
scales |
See |
strip |
See |
groups |
See |
xlab , ylab
|
See |
xlim , ylim
|
See |
drop.unused.levels |
See |
lattice.options |
See |
default.scales |
See |
subscripts |
See |
subset |
See |
default.prepanel |
Fallback prepanel function. See |
weights |
numeric vector of weights for the density
calculations, evaluated in the non-standard manner used for
At the time of writing, |
bw , adjust , width
|
Arguments controlling bandwidth. Passed on as arguments to
|
kernel , window
|
The choice of kernel. Passed on as arguments to
|
give.Rkern |
Logical flag, passed on as argument to |
from , to , cut
|
Controls range over which density is evaluated. Passed on as
arguments to |
na.rm |
Logical flag specifying whether |
... |
Further arguments. See corresponding entry in
|
histogram
draws Conditional Histograms, and densityplot
draws Conditional Kernel Density Plots. The default panel function
uses the density
function to compute the density
estimate, and all arguments accepted by density
can be
specified in the call to densityplot
to control the output.
See documentation of density
for details.
These and all other high level Trellis functions have several
arguments in common. These are extensively documented only in the
help page for xyplot
, which should be consulted to learn more
detailed usage.
do.breaks
is an utility function that calculates breakpoints
given an interval and the number of pieces to break it into.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
The form of the arguments accepted by the default panel function
panel.histogram
is different from that in S-PLUS. Whereas
S-PLUS calculates the heights inside histogram
and passes only
the breakpoints and the heights to the panel function, lattice
simply passes along the original variable x
along with the
breakpoints. This approach is more flexible; see the example below
with an estimated density superimposed over the histogram.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
xyplot
,
panel.histogram
,
density
,
panel.densityplot
,
panel.mathdensity
,
Lattice
require(stats) histogram( ~ height | voice.part, data = singer, nint = 17, endpoints = c(59.5, 76.5), layout = c(2,4), aspect = 1, xlab = "Height (inches)") histogram( ~ height | voice.part, data = singer, xlab = "Height (inches)", type = "density", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, col = "black", args = list(mean=mean(x),sd=sd(x))) } ) densityplot( ~ height | voice.part, data = singer, layout = c(2, 4), xlab = "Height (inches)", bw = 5)
require(stats) histogram( ~ height | voice.part, data = singer, nint = 17, endpoints = c(59.5, 76.5), layout = c(2,4), aspect = 1, xlab = "Height (inches)") histogram( ~ height | voice.part, data = singer, xlab = "Height (inches)", type = "density", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, col = "black", args = list(mean=mean(x),sd=sd(x))) } ) densityplot( ~ height | voice.part, data = singer, layout = c(2, 4), xlab = "Height (inches)", bw = 5)
Draw quantile-Quantile plots of a sample against a theoretical distribution, possibly conditioned on other variables.
qqmath(x, data, ...) ## S3 method for class 'formula' qqmath(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), distribution = qnorm, f.value = NULL, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.qqmath"), prepanel = NULL, scales, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qqmath"), subscripts, subset) ## S3 method for class 'data.frame' qqmath(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' qqmath(x, data = NULL, ylab, ...)
qqmath(x, data, ...) ## S3 method for class 'formula' qqmath(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), distribution = qnorm, f.value = NULL, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", panel = lattice.getOption("panel.qqmath"), prepanel = NULL, scales, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qqmath"), subscripts, subset) ## S3 method for class 'data.frame' qqmath(x, data = NULL, formula = data, ...) ## S3 method for class 'numeric' qqmath(x, data = NULL, ylab, ...)
x |
The object on which method dispatch is carried out. For the |
data |
For the |
formula |
The formula to be used for the |
distribution |
A quantile function that takes a vector of probabilities as argument
and produces the corresponding quantiles from a theoretical
distribution. Possible values are |
f.value |
An optional numeric vector of probabilities, quantiles corresponding
to which should be plotted. This can also be a function of a single
integer (representing sample size) that returns such a numeric
vector. A typical value for this argument is the function
For large |
panel |
A function, called once for each panel, that uses the packet (subset
of panel variables) corresponding to the panel to create a display.
The default panel function |
allow.multiple , outer
|
See |
auto.key |
See |
aspect |
See |
prepanel |
See |
scales |
See |
strip |
See |
groups |
See |
xlab , ylab
|
See |
xlim , ylim
|
See |
drop.unused.levels |
See |
lattice.options |
See |
default.scales |
See |
subscripts |
See |
subset |
See |
default.prepanel |
Fallback prepanel function. See |
... |
Further arguments. See corresponding entry in |
qqmath
produces Q-Q plots of the given sample against a
theoretical distribution. The default behaviour of qqmath
is
different from the corresponding S-PLUS function, but is similar to
qqnorm
. See the entry for f.value
for specifics.
The implementation details are also different from S-PLUS. In
particular, all the important calculations are done by the panel (and
prepanel function) and not qqmath
itself. In fact, both the
arguments distribution
and f.value
are passed unchanged
to the panel and prepanel function. This allows, among other things,
display of grouped Q-Q plots, which are often useful. See the help
page for panel.qqmath
for further details.
This and all other high level Trellis functions have several arguments
in common. These are extensively documented only in the help page for
xyplot
, which should be consulted to learn more detailed
usage.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
xyplot
, panel.qqmath
,
panel.qqmathline
, prepanel.qqmathline
,
Lattice
, quantile
qqmath(~ rnorm(100), distribution = function(p) qt(p, df = 10)) qqmath(~ height | voice.part, aspect = "xy", data = singer, prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) }) vp.comb <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 1), levels = c("Bass", "Tenor", "Alto", "Soprano")) vp.group <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 2)) qqmath(~ height | vp.comb, data = singer, groups = vp.group, auto.key = list(space = "right"), aspect = "xy", prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) })
qqmath(~ rnorm(100), distribution = function(p) qt(p, df = 10)) qqmath(~ height | voice.part, aspect = "xy", data = singer, prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) }) vp.comb <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 1), levels = c("Bass", "Tenor", "Alto", "Soprano")) vp.group <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 2)) qqmath(~ height | vp.comb, data = singer, groups = vp.group, auto.key = list(space = "right"), aspect = "xy", prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) })
Quantile-Quantile plots for comparing two Distributions
qq(x, data, ...) ## S3 method for class 'formula' qq(x, data, aspect = "fill", panel = lattice.getOption("panel.qq"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, f.value = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, qtype = 7, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qq"), subscripts, subset) ## S3 method for class 'data.frame' qq(x, data = NULL, formula = data, ...)
qq(x, data, ...) ## S3 method for class 'formula' qq(x, data, aspect = "fill", panel = lattice.getOption("panel.qq"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, f.value = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, qtype = 7, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qq"), subscripts, subset) ## S3 method for class 'data.frame' qq(x, data = NULL, formula = data, ...)
x |
The object on which method dispatch is carried out. For the |
data |
For the |
formula |
The formula to be used for the |
f.value |
An optional numeric vector of probabilities, quantiles corresponding
to which should be plotted. This can also be a function of a single
integer (representing sample size) that returns such a numeric
vector. A typical value for this argument is the function
f.value = function(n) ppoints(n, a = 1) This has the effect of including the minimum and maximum data values
in the computed quantiles. This is similar to what happens for
For large |
panel |
A function, called once for each panel, that uses the packet (subset
of panel variables) corresponding to the panel to create a display.
The default panel function |
qtype |
The |
aspect |
See |
prepanel |
See |
scales |
See |
strip |
See |
groups |
See |
xlab , ylab
|
See |
xlim , ylim
|
See |
drop.unused.levels |
See |
lattice.options |
See |
default.scales |
See |
subscripts |
See |
subset |
See |
default.prepanel |
Fallback prepanel function. See |
... |
Further arguments. See corresponding entry in |
qq
produces Q-Q plots of two samples. The default behaviour of
qq
is different from the corresponding S-PLUS function. See the
entry for f.value
for specifics.
This and all other high level Trellis functions have several
arguments in common. These are extensively documented only in the
help page for xyplot
, which should be consulted to learn more
detailed usage.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
xyplot
, panel.qq
,
qqmath
, Lattice
qq(voice.part ~ height, aspect = 1, data = singer, subset = (voice.part == "Bass 2" | voice.part == "Tenor 1"))
qq(voice.part ~ height, aspect = 1, data = singer, subset = (voice.part == "Bass 2" | voice.part == "Tenor 1"))
Draws false color level plots and contour plots.
levelplot(x, data, ...) contourplot(x, data, ...) ## S3 method for class 'formula' levelplot(x, data, allow.multiple = is.null(groups) || outer, outer = TRUE, aspect = "fill", panel = if (useRaster) lattice.getOption("panel.levelplot.raster") else lattice.getOption("panel.levelplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, at, cuts = 15, pretty = FALSE, region = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., useRaster = FALSE, lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.levelplot"), colorkey = region, col.regions, alpha.regions, subset = TRUE) ## S3 method for class 'formula' contourplot(x, data, panel = lattice.getOption("panel.contourplot"), default.prepanel = lattice.getOption("prepanel.default.contourplot"), cuts = 7, labels = TRUE, contour = TRUE, pretty = TRUE, region = FALSE, ...) ## S3 method for class 'data.frame' levelplot(x, data = NULL, formula = data, ...) ## S3 method for class 'data.frame' contourplot(x, data = NULL, formula = data, ...) ## S3 method for class 'table' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'table' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'matrix' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'matrix' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'array' levelplot(x, data = NULL, ...) ## S3 method for class 'array' contourplot(x, data = NULL, ...)
levelplot(x, data, ...) contourplot(x, data, ...) ## S3 method for class 'formula' levelplot(x, data, allow.multiple = is.null(groups) || outer, outer = TRUE, aspect = "fill", panel = if (useRaster) lattice.getOption("panel.levelplot.raster") else lattice.getOption("panel.levelplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, at, cuts = 15, pretty = FALSE, region = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., useRaster = FALSE, lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.levelplot"), colorkey = region, col.regions, alpha.regions, subset = TRUE) ## S3 method for class 'formula' contourplot(x, data, panel = lattice.getOption("panel.contourplot"), default.prepanel = lattice.getOption("prepanel.default.contourplot"), cuts = 7, labels = TRUE, contour = TRUE, pretty = TRUE, region = FALSE, ...) ## S3 method for class 'data.frame' levelplot(x, data = NULL, formula = data, ...) ## S3 method for class 'data.frame' contourplot(x, data = NULL, formula = data, ...) ## S3 method for class 'table' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'table' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'matrix' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'matrix' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'array' levelplot(x, data = NULL, ...) ## S3 method for class 'array' contourplot(x, data = NULL, ...)
x |
for the Calculations are based on the assumption that all x and y values are evaluated on a grid (defined by their unique values). The function will not return an error if this is not true, but the display might not be meaningful. However, the x and y values need not be equally spaced. Both |
data |
For the |
formula |
The formula to be used for the |
row.values , column.values
|
Optional vectors of values that
define the grid when |
panel |
panel function used to create the display, as described in
|
aspect |
For the |
at |
A numeric vector giving breakpoints along the range of
|
col.regions |
color vector to be used if regions is TRUE. The
general idea is that this should be a color vector of moderately
large length (longer than the number of regions. By default this is
100). It is expected that this vector would be gradually varying in
color (so that nearby colors would be similar). When the colors are
actually chosen, they are chosen to be equally spaced along this
vector. When there are more regions than colors in
|
alpha.regions |
Numeric, specifying alpha transparency (works only on some devices) |
colorkey |
A logical flag specifying whether a colorkey is to be drawn alongside the plot, or a list describing the colorkey. The list may contain the following components:
|
contour |
A logical flag, indicating whether to draw contour lines. |
cuts |
The number of levels the range of |
labels |
Typically a logical indicating whether contour lines should be
labelled, but other possibilities for more sophisticated control
exists. Details are documented in the help page for
|
pretty |
A logical flag, indicating whether to use pretty cut locations and labels. |
region |
A logical flag, indicating whether regions between contour lines should be filled as in a level plot. |
allow.multiple , outer , prepanel , scales , strip , groups , xlab , xlim , ylab , ylim , drop.unused.levels , lattice.options , default.scales , subset
|
These arguments are described in the help page for
|
default.prepanel |
Fallback prepanel function. See |
... |
Further arguments may be supplied. Some are processed by
|
useRaster |
A logical flag indicating whether raster representations should be
used, both for the false color image and the color key (if present).
Effectively, setting this to Note that Not all devices support raster images. For devices that appear to
lack support, |
These and all other high level Trellis functions have several
arguments in common. These are extensively documented only in the
help page for xyplot
, which should be consulted to learn more
detailed usage.
Other useful arguments are mentioned in the help page for the default
panel function panel.levelplot
(these are formally
arguments to the panel function, but can be specified in the high
level calls directly).
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
xyplot
, Lattice
,
panel.levelplot
x <- seq(pi/4, 5 * pi, length.out = 100) y <- seq(pi/4, 5 * pi, length.out = 100) r <- as.vector(sqrt(outer(x^2, y^2, "+"))) grid <- expand.grid(x=x, y=y) grid$z <- cos(r^2) * exp(-r/(pi^3)) levelplot(z ~ x * y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) ## triangular end-points in color key, with a title levelplot(z ~ x * y, grid, col.regions = hcl.colors(10), at = c(-Inf, seq(-0.8, 0.8, by = 0.2), Inf)) #S-PLUS example require(stats) attach(environmental) ozo.m <- loess((ozone^(1/3)) ~ wind * temperature * radiation, parametric = c("radiation", "wind"), span = 1, degree = 2) w.marginal <- seq(min(wind), max(wind), length.out = 50) t.marginal <- seq(min(temperature), max(temperature), length.out = 50) r.marginal <- seq(min(radiation), max(radiation), length.out = 4) wtr.marginal <- list(wind = w.marginal, temperature = t.marginal, radiation = r.marginal) grid <- expand.grid(wtr.marginal) grid[, "fit"] <- c(predict(ozo.m, grid)) contourplot(fit ~ wind * temperature | radiation, data = grid, cuts = 10, region = TRUE, xlab = "Wind Speed (mph)", ylab = "Temperature (F)", main = "Cube Root Ozone (cube root ppb)") detach()
x <- seq(pi/4, 5 * pi, length.out = 100) y <- seq(pi/4, 5 * pi, length.out = 100) r <- as.vector(sqrt(outer(x^2, y^2, "+"))) grid <- expand.grid(x=x, y=y) grid$z <- cos(r^2) * exp(-r/(pi^3)) levelplot(z ~ x * y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) ## triangular end-points in color key, with a title levelplot(z ~ x * y, grid, col.regions = hcl.colors(10), at = c(-Inf, seq(-0.8, 0.8, by = 0.2), Inf)) #S-PLUS example require(stats) attach(environmental) ozo.m <- loess((ozone^(1/3)) ~ wind * temperature * radiation, parametric = c("radiation", "wind"), span = 1, degree = 2) w.marginal <- seq(min(wind), max(wind), length.out = 50) t.marginal <- seq(min(temperature), max(temperature), length.out = 50) r.marginal <- seq(min(radiation), max(radiation), length.out = 4) wtr.marginal <- list(wind = w.marginal, temperature = t.marginal, radiation = r.marginal) grid <- expand.grid(wtr.marginal) grid[, "fit"] <- c(predict(ozo.m, grid)) contourplot(fit ~ wind * temperature | radiation, data = grid, cuts = 10, region = TRUE, xlab = "Wind Speed (mph)", ylab = "Temperature (F)", main = "Cube Root Ozone (cube root ppb)") detach()
Generic functions to draw 3d scatter plots and surfaces. The
"formula"
methods do most of the actual work.
cloud(x, data, ...) wireframe(x, data, ...) ## S3 method for class 'formula' cloud(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = lattice.getOption("default.args")$auto.key, aspect = c(1,1), panel.aspect = 1, panel = lattice.getOption("panel.cloud"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, ylab, zlab, xlim = if (is.factor(x)) levels(x) else range(x, finite = TRUE), ylim = if (is.factor(y)) levels(y) else range(y, finite = TRUE), zlim = if (is.factor(z)) levels(z) else range(z, finite = TRUE), at, drape = FALSE, pretty = FALSE, drop.unused.levels, ..., lattice.options = NULL, default.scales = list(distance = c(1, 1, 1), arrows = TRUE, axs = axs.default), default.prepanel = lattice.getOption("prepanel.default.cloud"), colorkey, col.regions, alpha.regions, cuts = 70, subset = TRUE, axs.default = "r") ## S3 method for class 'data.frame' cloud(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' wireframe(x, data, panel = lattice.getOption("panel.wireframe"), default.prepanel = lattice.getOption("prepanel.default.wireframe"), ...) ## S3 method for class 'data.frame' wireframe(x, data = NULL, formula = data, ...) ## S3 method for class 'matrix' cloud(x, data = NULL, type = "h", zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values) ## S3 method for class 'table' cloud(x, data = NULL, groups = FALSE, zlab = deparse(substitute(x)), type = "h", ...) ## S3 method for class 'matrix' wireframe(x, data = NULL, zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values)
cloud(x, data, ...) wireframe(x, data, ...) ## S3 method for class 'formula' cloud(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = lattice.getOption("default.args")$auto.key, aspect = c(1,1), panel.aspect = 1, panel = lattice.getOption("panel.cloud"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, ylab, zlab, xlim = if (is.factor(x)) levels(x) else range(x, finite = TRUE), ylim = if (is.factor(y)) levels(y) else range(y, finite = TRUE), zlim = if (is.factor(z)) levels(z) else range(z, finite = TRUE), at, drape = FALSE, pretty = FALSE, drop.unused.levels, ..., lattice.options = NULL, default.scales = list(distance = c(1, 1, 1), arrows = TRUE, axs = axs.default), default.prepanel = lattice.getOption("prepanel.default.cloud"), colorkey, col.regions, alpha.regions, cuts = 70, subset = TRUE, axs.default = "r") ## S3 method for class 'data.frame' cloud(x, data = NULL, formula = data, ...) ## S3 method for class 'formula' wireframe(x, data, panel = lattice.getOption("panel.wireframe"), default.prepanel = lattice.getOption("prepanel.default.wireframe"), ...) ## S3 method for class 'data.frame' wireframe(x, data = NULL, formula = data, ...) ## S3 method for class 'matrix' cloud(x, data = NULL, type = "h", zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values) ## S3 method for class 'table' cloud(x, data = NULL, groups = FALSE, zlab = deparse(substitute(x)), type = "h", ...) ## S3 method for class 'matrix' wireframe(x, data = NULL, zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values)
x |
The object on which method dispatch is carried out. For the For Missing values are allowed, either as Both |
data |
For the |
formula |
The formula to be used for the |
row.values , column.values
|
Optional vectors of values that
define the grid when |
allow.multiple , outer , auto.key , prepanel , strip , groups , xlab , xlim , ylab , ylim , drop.unused.levels , lattice.options , default.scales , subset
|
These arguments are documented in the help page for
|
type |
type of display in |
aspect , panel.aspect
|
Unlike other high level functions, For the |
panel |
panel function used to create the display. See
|
default.prepanel |
Fallback prepanel function. See |
scales |
a list describing the scales. As with other high level functions
(see The most common use for this argument is to set Other components that work in the Note, however, that for these functions |
axs.default |
Unlike 2-D display functions, |
zlab |
Specifies a label describing the z variable in ways similar to
|
zlim |
limits for the z-axis. Similar to |
drape |
logical, whether the wireframe is to be draped in color. If
|
at , col.regions , alpha.regions
|
these arguments are analogous to those in
|
cuts |
if |
pretty |
whether automatic choice of cutpoints should be prettfied |
colorkey |
logical indicating whether a color key should be drawn
alongside, or a list describing such a key. See
|
... |
Any number of other arguments can be specified, and are passed to
the panel function. In particular, the arguments Additionally, an argument called |
These functions produce three dimensional plots in each panel (as long
as the default panel functions are used). The orientation is obtained
as follows: the data are scaled to fall within a bounding box that is
contained in the [-0.5, 0.5] cube (even smaller for non-default values
of aspect
). The viewing direction is given by a sequence of
rotations specified by the screen
argument, starting from the
positive Z-axis. The viewing point (camera) is located at a distance
of 1/distance
from the origin. If perspective=FALSE
,
distance
is set to 0 (i.e., the viewing point is at an infinite
distance).
cloud
draws a 3-D Scatter Plot, while wireframe
draws a
3-D surface (usually evaluated on a grid). Multiple surfaces can be
drawn by wireframe
using the groups
argument (although
this is of limited use because the display is incorrect when the
surfaces intersect). Specifying groups
with cloud
results in a panel.superpose
-like effect (via
panel.3dscatter
).
wireframe
can optionally render the surface as being
illuminated by a light source (no shadows though). Details can be
found in the help page for panel.3dwire
. Note that
although arguments controlling these are actually arguments for the
panel function, they can be supplied to cloud
and
wireframe
directly.
For single panel plots, wireframe
can also plot parametrized
3-D surfaces (i.e., functions of the form f(u,v) = (x(u,v), y(u,v),
z(u,v)), where values of (u,v) lie on a rectangle. The simplest
example of this sort of surface is a sphere parametrized by latitude
and longitude. This can be achieved by calling wireframe
with a
formula x
of the form z~x*y
, where x
, y
and z
are all matrices of the same dimension, representing the
values of x(u,v), y(u,v) and z(u,v) evaluated on a discrete
rectangular grid (the actual values of (u,v) are irrelevant).
When this feature is used, the heights used to calculate drape
colors or shading colors are no longer the z
values, but the
distances of (x,y,z)
from the origin.
Note that this feature does not work with groups
,
subscripts
, subset
, etc. Conditioning variables are also
not supported in this case.
The algorithm for identifying which edges of the bounding box are
‘behind’ the points doesn't work in some extreme
situations. Also, panel.cloud
tries to figure out the
optimal location of the arrows and axis labels automatically, but can
fail on occasion (especially when the view is from ‘below’ the
data). This can be manually controlled by the scpos
argument in
panel.cloud
.
These and all other high level Trellis functions have several other
arguments in common. These are extensively documented only in the
help page for xyplot
, which should be consulted to learn
more detailed usage.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
There is a known problem with grouped wireframe
displays
when the (x, y) coordinates represented in the data do not represent
the full evaluation grid. The problem occurs whether the grouping is
specified through the groups
argument or through the formula
interface, and currently causes memory access violations. Depending
on the circumstances, this is manifested either as a meaningless plot
or a crash. To work around the problem, it should be enough to have
a row in the data frame for each grid point, with an NA
response (z
) in rows that were previously missing.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
Lattice
for an overview of the package, as well as
xyplot
, levelplot
,
panel.cloud
.
For interaction, see panel.identify.cloud
.
## volcano ## 87 x 61 matrix wireframe(volcano, shade = TRUE, aspect = c(61/87, 0.4), light.source = c(10,0,10)) g <- expand.grid(x = 1:10, y = 5:15, gr = 1:2) g$z <- log((g$x^g$gr + g$y^2) * g$gr) wireframe(z ~ x * y, data = g, groups = gr, scales = list(arrows = FALSE), drape = TRUE, colorkey = TRUE, screen = list(z = 30, x = -60)) cloud(Sepal.Length ~ Petal.Length * Petal.Width | Species, data = iris, screen = list(x = -90, y = 70), distance = .4, zoom = .6) ## cloud.table cloud(prop.table(Titanic, margin = 1:3), type = c("p", "h"), strip = strip.custom(strip.names = TRUE), scales = list(arrows = FALSE, distance = 2), panel.aspect = 0.7, zlab = "Proportion")[, 1] ## transparent axes par.set <- list(axis.line = list(col = "transparent"), clip = list(panel = "off")) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 3), par.settings = par.set, scales = list(col = "black")), split = c(1,1,2,1), more = TRUE) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 0), par.settings = par.set, scales = list(col = "black")), split = c(2,1,2,1))
## volcano ## 87 x 61 matrix wireframe(volcano, shade = TRUE, aspect = c(61/87, 0.4), light.source = c(10,0,10)) g <- expand.grid(x = 1:10, y = 5:15, gr = 1:2) g$z <- log((g$x^g$gr + g$y^2) * g$gr) wireframe(z ~ x * y, data = g, groups = gr, scales = list(arrows = FALSE), drape = TRUE, colorkey = TRUE, screen = list(z = 30, x = -60)) cloud(Sepal.Length ~ Petal.Length * Petal.Width | Species, data = iris, screen = list(x = -90, y = 70), distance = .4, zoom = .6) ## cloud.table cloud(prop.table(Titanic, margin = 1:3), type = c("p", "h"), strip = strip.custom(strip.names = TRUE), scales = list(arrows = FALSE, distance = 2), panel.aspect = 0.7, zlab = "Proportion")[, 1] ## transparent axes par.set <- list(axis.line = list(col = "transparent"), clip = list(panel = "off")) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 3), par.settings = par.set, scales = list(col = "black")), split = c(1,1,2,1), more = TRUE) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 0), par.settings = par.set, scales = list(col = "black")), split = c(2,1,2,1))
Draw Conditional Scatter Plot Matrices and Parallel Coordinate Plots
splom(x, data, ...) parallelplot(x, data, ...) ## S3 method for class 'formula' splom(x, data, auto.key = lattice.getOption("default.args")$auto.key, aspect = 1, between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.splom"), prepanel, scales, strip, groups, xlab, xlim, ylab = NULL, ylim, superpanel = lattice.getOption("panel.pairs"), pscales = 5, varnames = NULL, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.splom"), subset = TRUE) ## S3 method for class 'formula' parallelplot(x, data, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.parallel"), prepanel, scales, strip, groups, xlab = NULL, xlim, ylab = NULL, ylim, varnames = NULL, horizontal.axis = TRUE, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.parallel"), subset = TRUE) ## S3 method for class 'data.frame' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'data.frame' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE)
splom(x, data, ...) parallelplot(x, data, ...) ## S3 method for class 'formula' splom(x, data, auto.key = lattice.getOption("default.args")$auto.key, aspect = 1, between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.splom"), prepanel, scales, strip, groups, xlab, xlim, ylab = NULL, ylim, superpanel = lattice.getOption("panel.pairs"), pscales = 5, varnames = NULL, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.splom"), subset = TRUE) ## S3 method for class 'formula' parallelplot(x, data, auto.key = lattice.getOption("default.args")$auto.key, aspect = "fill", between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.parallel"), prepanel, scales, strip, groups, xlab = NULL, xlim, ylab = NULL, ylim, varnames = NULL, horizontal.axis = TRUE, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.parallel"), subset = TRUE) ## S3 method for class 'data.frame' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'data.frame' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE)
x |
The object on which method dispatch is carried out. For the For the |
data |
For the |
aspect |
aspect ratio of each panel (and subpanel), square by default for
|
between |
to avoid confusion between panels and subpanels, the default is to show the panels of a splom plot with space between them. |
panel |
For For |
superpanel |
function that sets up the splom display, by default as a scatterplot matrix. |
pscales |
a numeric value or a list, meant to be a less functional substitute
for the |
varnames |
A character or expression vector or giving names to be used for the
variables in |
horizontal.axis |
logical indicating whether the parallel axes should
be laid out horizontally ( |
auto.key , prepanel , scales , strip , groups , xlab , xlim , ylab , ylim , drop.unused.levels , lattice.options , default.scales , subset
|
See |
default.prepanel |
Fallback prepanel function. See |
... |
Further arguments. See corresponding entry in
|
splom
produces Scatter Plot Matrices. The role usually played
by panel
is taken over by superpanel
, which takes a data
frame subset and is responsible for plotting it. It is called with
the coordinate system set up to have both x- and y-limits from
0.5
to ncol(z) + 0.5
. The only built-in option
currently available is panel.pairs
, which calls a
further panel function for each pair (i, j)
of variables in
z
inside a rectangle of unit width and height centered at
c(i, j)
(see panel.pairs
for details).
Many of the finer customizations usually done via arguments to high
level function like xyplot
are instead done by
panel.pairs
for splom
. These include control of axis
limits, tick locations and prepanel calcultions. If you are trying to
fine-tune your splom
plot, definitely look at the
panel.pairs
help page. The scales
argument is
usually not very useful in splom
, and trying to change it may
have undesired effects.
parallelplot
draws Parallel Coordinate Plots. (Difficult to
describe, see example.)
These and all other high level Trellis functions have several
arguments in common. These are extensively documented only in the
help page for xyplot
, which should be consulted to learn more
detailed usage.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
xyplot
, Lattice
, panel.pairs
,
panel.parallel
.
super.sym <- trellis.par.get("superpose.symbol") splom(~iris[1:4], groups = Species, data = iris, panel = panel.superpose, key = list(title = "Three Varieties of Iris", columns = 3, points = list(pch = super.sym$pch[1:3], col = super.sym$col[1:3]), text = list(c("Setosa", "Versicolor", "Virginica")))) splom(~iris[1:3]|Species, data = iris, layout=c(2,2), pscales = 0, varnames = c("Sepal\nLength", "Sepal\nWidth", "Petal\nLength"), page = function(...) { ltext(x = seq(.6, .8, length.out = 4), y = seq(.9, .6, length.out = 4), labels = c("Three", "Varieties", "of", "Iris"), cex = 2) }) parallelplot(~iris[1:4] | Species, iris) parallelplot(~iris[1:4], iris, groups = Species, horizontal.axis = FALSE, scales = list(x = list(rot = 90)))
super.sym <- trellis.par.get("superpose.symbol") splom(~iris[1:4], groups = Species, data = iris, panel = panel.superpose, key = list(title = "Three Varieties of Iris", columns = 3, points = list(pch = super.sym$pch[1:3], col = super.sym$col[1:3]), text = list(c("Setosa", "Versicolor", "Virginica")))) splom(~iris[1:3]|Species, data = iris, layout=c(2,2), pscales = 0, varnames = c("Sepal\nLength", "Sepal\nWidth", "Petal\nLength"), page = function(...) { ltext(x = seq(.6, .8, length.out = 4), y = seq(.9, .6, length.out = 4), labels = c("Three", "Varieties", "of", "Iris"), cex = 2) }) parallelplot(~iris[1:4] | Species, iris) parallelplot(~iris[1:4], iris, groups = Species, horizontal.axis = FALSE, scales = list(x = list(rot = 90)))
tmd
Creates Tukey Mean-Difference Plots from a trellis object
returned by xyplot
, qq
or qqmath
. The prepanel
and panel functions are used as appropriate. The formula
and
data.frame
methods for tmd
are provided for convenience,
and simply call tmd
on the object created by the corresponding
xyplot
methods.
tmd(object, ...) ## S3 method for class 'trellis' tmd(object, xlab = "mean", ylab = "difference", panel, prepanel, ...) prepanel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ...) panel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ..., identifier = "tmd") panel.tmd.default(x, y, groups = NULL, ..., identifier = "tmd") prepanel.tmd.default(x, y, ...)
tmd(object, ...) ## S3 method for class 'trellis' tmd(object, xlab = "mean", ylab = "difference", panel, prepanel, ...) prepanel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ...) panel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ..., identifier = "tmd") panel.tmd.default(x, y, groups = NULL, ..., identifier = "tmd") prepanel.tmd.default(x, y, ...)
object |
An object of class |
xlab |
x label |
ylab |
y label |
panel |
panel function to be used. See details below. |
prepanel |
prepanel function. See details below. |
f.value , distribution , qtype
|
see |
groups , subscripts
|
see |
x , y
|
data as passed to panel functions in original call. |
... |
other arguments |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
The Tukey Mean-difference plot is produced by modifying the (x,y)
values of each panel as follows: the new coordinates are given by
x=(x+y)/2
and y=y-x
, which are then plotted. The
default panel function(s) add a reference line at y=0
as well.
tmd
acts on the a "trellis"
object, not on the actual plot
this object would have produced. As such, it only uses the arguments
supplied to the panel function in the original call, and completely
ignores what the original panel function might have done with this
data. tmd
uses these panel arguments to set up its own scales
(using its prepanel
argument) and display (using
panel
). It is thus important to provide suitable prepanel and
panel functions to tmd
depending on the original call.
Such functions currently exist for xyplot
, qq
(the ones
with default
in their name) and qqmath
, as listed in the
usage section above. These assume the default displays for the
corresponding high-level call. If unspecified, the prepanel
and
panel
arguments default to suitable choices.
tmd
uses the update
method for "trellis"
objects,
which processes all extra arguments supplied to tmd
.
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
tmd(qqmath(~height | voice.part, data = singer))
tmd(qqmath(~height | voice.part, data = singer))
Plots fitted values and residuals (via qqmath) on a common scale for any object that has methods for fitted values and residuals.
rfs(model, layout=c(2, 1), xlab="f-value", ylab=NULL, distribution = qunif, panel, prepanel, strip, ...)
rfs(model, layout=c(2, 1), xlab="f-value", ylab=NULL, distribution = qunif, panel, prepanel, strip, ...)
model |
a fitted model object with methods |
layout |
default layout is c(2,1) |
xlab |
defaults to |
distribution |
the distribution function to be used for |
ylab , panel , prepanel , strip
|
See |
... |
other arguments, passed on to |
An object of class "trellis"
. The
update
method can be used to
update components of the object and the
print
method (usually called by
default) will plot it on an appropriate plotting device.
Deepayan Sarkar [email protected]
oneway
, qqmath
,
xyplot
, Lattice
rfs(oneway(height ~ voice.part, data = singer, spread = 1), aspect = 1)
rfs(oneway(height ~ voice.part, data = singer, spread = 1), aspect = 1)
Fits a One-way model to univariate data grouped by a factor, the
result often being displayed using rfs
oneway(formula, data, location=mean, spread=function(x) sqrt(var(x)))
oneway(formula, data, location=mean, spread=function(x) sqrt(var(x)))
formula |
formula of the form |
data |
data frame in which the model is to be evaluated |
location |
function or numeric giving the location statistic to
be used for centering the observations, e.g. |
spread |
function or numeric giving the spread statistic to
be used for scaling the observations, e.g. |
A list with components
location
vector of locations for each group.
spread
vector of spreads for each group.
fitted.values
vector of locations for each observation.
residuals
residuals (y - fitted.values
).
scaled.residuals
residuals scaled by spread
for their
group
Deepayan Sarkar [email protected]
Initialization of a display device with appropriate graphical parameters.
trellis.device(device = getOption("device"), color = !(dev.name == "postscript"), theme = lattice.getOption("default.theme"), new = TRUE, retain = FALSE, ...)
trellis.device(device = getOption("device"), color = !(dev.name == "postscript"), theme = lattice.getOption("default.theme"), new = TRUE, retain = FALSE, ...)
device |
function (or the name of one as a character string)
that starts a device. Admissible values depend on the platform and
how R was compiled (see |
color |
logical, whether the initial settings should be color or
black and white. Defaults to |
theme |
list of components that changes the settings of the device opened, or, a function that when called produces such a list. The function name can be supplied as a quoted string. These settings are only used to modify the default settings (determined by other arguments), and need not contain all possible parameters. A possible use of this argument is to change the default settings by
specifying If |
new |
logical flag indicating whether a new device should be
started. If |
retain |
logical. If |
name |
name of the device for which the setting is required, as
returned by |
... |
additional parameters to be passed to the |
The trellis.device
function sets up an R graphics device for
use with lattice graphics, by opening the device if necessary, and
defining a set of associated graphical parameters (colors, line types,
fonts, etc.).
Even if a device is opened without calling trellis.device
, for
example, by calling a device function directly, trellis.device
is still called automatically when a "trellis"
object is
plotted. The default graphical settings used in this case can be
customized using lattice.options
. It is therefore
rarely necessary for the user to call trellis.device
explicitly.
None; trellis.device
is called for the side effect of opening a
device and / or setting associated graphical parameters.
Earlier versions of trellis.device
had a bg
argument to
set the background color, but this is no longer supported. If
supplied, the bg
argument will be passed on to the device
function; however, this will have no effect on the Trellis settings.
It is rarely meaningful to change the background alone; if you feel
the need to change the background, consider using the theme
argument instead.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
Lattice
for an overview of the lattice
package.
Devices
for valid choices of device
on your
platform.
standard.theme
for the default theme and alternatives.
Built-in graphical parameter settings. These mainly differ in their choice of colors.
standard.theme(name, color = TRUE, symbol = palette.colors(palette = "Okabe-Ito")[c(6, 2, 4, 7, 3, 5, 8)], fill = NULL, region = hcl.colors(14, palette = "YlGnBu", rev = TRUE), reference = "gray90", bg = "transparent", fg = "black", ...) canonical.theme(...) custom_theme(symbol, fill, region, reference = "gray90", bg = "transparent", fg = "black", strip.bg = rep("gray95", 7), strip.fg = rep("gray70", 7), ...) classic.theme(name, color) col.whitebg()
standard.theme(name, color = TRUE, symbol = palette.colors(palette = "Okabe-Ito")[c(6, 2, 4, 7, 3, 5, 8)], fill = NULL, region = hcl.colors(14, palette = "YlGnBu", rev = TRUE), reference = "gray90", bg = "transparent", fg = "black", ...) canonical.theme(...) custom_theme(symbol, fill, region, reference = "gray90", bg = "transparent", fg = "black", strip.bg = rep("gray95", 7), strip.fg = rep("gray70", 7), ...) classic.theme(name, color) col.whitebg()
name |
character string giving the name of the device for which
the setting is required, as returned by |
color |
logical, whether the initial settings should be color or black and white. |
symbol |
vector of colors to be used for symbols and lines. |
fill |
vector of colors to be used as fill colors, e.g., in bar
charts and histograms. The default of |
region |
vector of colors to be used to create a color ramp,
typically used by |
reference |
color, to be used for reference lines. |
fg |
color, to be used for foreground elements such as axes and labels. |
bg |
color, to be used as background. |
strip.bg |
color, to be used as strip background. |
strip.fg |
color, to be used as strip foreground. |
... |
additional arguments, passed on to other functions as
appropriate. In particular, additional arguments provided to
|
Trellis Graphics functions obtain the default values of various
graphical parameters (colors, line types, fonts, etc.) from a
customizable “settings” list (see trellis.par.set
for details). This functionality is analogous to par
for standard R graphics and, together with
lattice.options
, mostly supplants it (par
settings are mostly ignored by Lattice). Unlike par
,
Trellis settings can be controlled separately for each different
device type (but not concurrently for different instances of the same
device).
The functions documented in this page produce such graphical settings
(a.k.a. themes), usually to be used with trellis.device
or trellis.par.set
.
classic.theme
and col.whitebg
produce predefined themes
that are not recommended for routine use but are retained for
compatibility.
The classic.theme
function was intended to provide device
specific settings (e.g. light colors on a grey background for screen
devices, dark colors or black and white for print devices) and was
used to obtain defaults prior to R 2.3.0. However, these settings
are not always appropriate, due to the variety of platforms and
hardware settings on which R is used, as well as the fact that a plot
created on a particular device may be subsequently used in many
different ways. For this reason, common device-agnostic defaults were
used for all devices from R 2.3.0 onwards.
Since R 4.3.0, a new set of defaults given by standard.theme
is used. The defaults are based on HCL palettes, but customization of
the palettes is allowed. Earlier behaviour can be reinstated by
setting classic.theme
as the default theme
argument,
e.g., by putting
lattice.options(default.theme = classic.theme("pdf"))
in a startup script (see the entry for theme
in
trellis.device
for details).
custom_theme
is the workhorse function called by
standard.theme
. canonical.theme
is an alias for
standard.theme
.
A list of components defining graphical parameter settings for Lattice
displays. It is used internally in trellis.device
, and can also
be used as the theme
argument to trellis.par.set
col.whitebg
returns a similar (but smaller) list that is
suitable as the theme
argument to trellis.device
and
trellis.par.set
. It contains settings values which
provide colors suitable for plotting on a white background. Note that
the name col.whitebg
is somewhat of a misnomer, since it
actually sets the background to transparent rather than white.
Deepayan Sarkar [email protected]
Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/
Lattice
for an overview of the lattice
package.
Devices
for valid choices of device
on your
platform.
trellis.par.get
and trellis.par.set
can be
used to query and modify the settings after a device has been
initialized. The par.settings
argument to high level
functions, described in xyplot
, can be used to attach
transient settings to a "trellis"
object.
Functions used to query, display and modify graphical parameters for fine control of Trellis displays. Modifications are made to the settings for the currently active device only.
trellis.par.set(name, value, ..., theme, warn = TRUE, strict = FALSE) trellis.par.get(name = NULL) show.settings(x = NULL)
trellis.par.set(name, value, ..., theme, warn = TRUE, strict = FALSE) trellis.par.get(name = NULL) show.settings(x = NULL)
name |
A character string giving the name of a component. If unspecified
in |
value |
a list giving the desired value of the component. Components that
are already defined as part of the current settings but are not
mentioned in |
theme |
a list decribing how to change the settings, similar to what is
returned by As in |
... |
Multiple settings can be specified in |
warn |
A logical flag, indicating whether a warning should be issued when
|
strict |
Usually a logical flag, indicating whether the An even stricter interpretation is allowed by specifying
|
x |
optional list of components that change the settings (any valid
value of |
The various graphical parameters (color, line type, background etc)
that control the look and feel of Trellis displays are highly
customizable. Also, R can produce graphics on a number of devices, and
it is expected that a different set of parameters would be more suited
to different devices. These parameters are stored internally in a
variable named lattice.theme
, which is a list whose components
define settings for particular devices. The components are idenified
by the name of the device they represent (as obtained by
.Device
), and are created as and when new devices are opened
for the first time using trellis.device
(or Lattice plots are
drawn on a device for the first time in that session).
The initial settings for each device defaults to values appropriate
for that device. In practice, this boils down to three distinct
settings, one for screen devices like x11
and windows
,
one for black and white plots (mostly useful for postscript
)
and one for color printers (color postcript
, pdf
).
Once a device is open, its settings can be modified. When another
instance of the same device is opened later using
trellis.device
, the settings for that device are reset to its
defaults, unless otherwise specified in the call to
trellis.device
. But settings for different devices are treated
separately, i.e., opening a postscript device will not alter the x11
settings, which will remain in effect whenever an x11 device is
active.
The functions trellis.par.*
are meant to be interfaces to the
global settings. They always apply on the settings for the currently
ACTIVE device.
trellis.par.get
, called without any arguments, returns the full
list of settings for the active device. With the name
argument
present, it returns that component only. trellis.par.get
sets
the value of the name
component of the current active device
settings to value
.
trellis.par.get
is usually used inside trellis functions to get
graphical parameters before plotting. Modifications by users via
trellis.par.set
is traditionally done as follows:
add.line <- trellis.par.get("add.line")
add.line$col <- "red"
trellis.par.set("add.line", add.line)
More convenient (but not S compatible) ways to do this are
trellis.par.set(list(add.line = list(col = "red")))
and
trellis.par.set(add.line = list(col = "red"))
The actual list of the components in trellis.settings
has not
been finalized, so I'm not attempting to list them here. The current
value can be obtained by print(trellis.par.get())
. Most names
should be self-explanatory.
show.settings
provides a graphical display summarizing some of
the values in the current settings.
trellis.par.get
returns a list giving parameters for that
component. If name
is missing, it returns the full list.
Most of the settings are graphical parameters that control various elements of a lattice plot. For details, see the examples below. The more unusual settings are described here.
grid.pars
Grid graphical parameters that are in effect globally unless overridden by specific settings.
fontsize
A list of two components (each a numeric scalar),
text
and points
, for text and symbols
respectively.
clip
A list of two components (each a character string,
either "on"
or "off"
), panel
and
strip
.
axis.components
A list with four components (left
,
top
, right
, bottom
), each a list giving numeric
mutlipliers named tck
, pad1
, and pad2
for
corresponding grid layout units.
layout.heights
A list with numeric multipliers for grid layout heights.
layout.widths
A list with numeric multipliers for grid layout widths.
In some ways, trellis.par.get
and trellis.par.set
together are a replacement for the par
function used in
traditional R graphics. In particular, changing par
settings
has little (if any) effect on lattice output. Since lattice plots are
implemented using Grid graphics, its parameter system does have
an effect unless overridden by a suitable lattice parameter setting.
Such parameters can be specified as part of a lattice theme by
including them in the grid.pars
component (see
gpar
for a list of valid parameter names).
Deepayan Sarkar [email protected]
show.settings() tp <- trellis.par.get() unusual <- c("grid.pars", "fontsize", "clip", "axis.components", "layout.heights", "layout.widths") for (u in unusual) tp[[u]] <- NULL names.tp <- lapply(tp, names) unames <- sort(unique(unlist(names.tp))) ans <- matrix(0, nrow = length(names.tp), ncol = length(unames)) rownames(ans) <- names(names.tp) colnames(ans) <- unames for (i in seq_along(names.tp)) ans[i, ] <- as.numeric(unames %in% names.tp[[i]]) ans <- ans[, order(-colSums(ans))] ans <- ans[order(rowSums(ans)), ] ans[ans == 0] <- NA levelplot(t(ans), colorkey = FALSE, scales = list(x = list(rot = 90)), panel = function(x, y, z, ...) { panel.abline(v = unique(as.numeric(x)), h = unique(as.numeric(y)), col = "darkgrey") panel.xyplot(x, y, pch = 16 * z, ...) }, xlab = "Graphical parameters", ylab = "Setting names")
show.settings() tp <- trellis.par.get() unusual <- c("grid.pars", "fontsize", "clip", "axis.components", "layout.heights", "layout.widths") for (u in unusual) tp[[u]] <- NULL names.tp <- lapply(tp, names) unames <- sort(unique(unlist(names.tp))) ans <- matrix(0, nrow = length(names.tp), ncol = length(unames)) rownames(ans) <- names(names.tp) colnames(ans) <- unames for (i in seq_along(names.tp)) ans[i, ] <- as.numeric(unames %in% names.tp[[i]]) ans <- ans[, order(-colSums(ans))] ans <- ans[order(rowSums(ans)), ] ans[ans == 0] <- NA levelplot(t(ans), colorkey = FALSE, scales = list(x = list(rot = 90)), panel = function(x, y, z, ...) { panel.abline(v = unique(as.numeric(x)), h = unique(as.numeric(y)), col = "darkgrey") panel.xyplot(x, y, pch = 16 * z, ...) }, xlab = "Graphical parameters", ylab = "Setting names")
Simple interface to generate a list appropriate as a theme, typically
used as the par.settings
argument in a high level call
simpleTheme(col, alpha, cex, pch, lty, lwd, font, fill, border, col.points, col.line, alpha.points, alpha.line)
simpleTheme(col, alpha, cex, pch, lty, lwd, font, fill, border, col.points, col.line, alpha.points, alpha.line)
col , col.points , col.line
|
A color specification. |
alpha , alpha.points , alpha.line
|
A numeric alpha transparency specification. The same rules as
|
cex , pch , font
|
Parameters for points. Applicable for
components |
lty , lwd
|
Parameters for lines. Applicable for
components |
fill |
fill color, applicable for components |
border |
border color, applicable for components
|
The appearance of a lattice display depends partly on the
“theme” active when the display is plotted (see
trellis.device
for details). This theme is used to
obtain defaults for various graphical parameters, and in particular,
the auto.key
argument works on the premise that the same source
is used for both the actual graphical encoding and the legend. The
easiest way to specify custom settings for a particular display is to
use the par.settings
argument, which is usually tedious to
construct as it is a nested list. The simpleTheme
function can
be used in such situations as a wrapper that generates a suitable list
given parameters in simple name=value
form, with the nesting
made implicit. This is less flexible, but straightforward and
sufficient in most situations.
A list that would work as the theme
argument to
trellis.device
and trellis.par.set
, or
as the par.settings
argument to any high level lattice function
such as xyplot
.
Deepayan Sarkar [email protected], based on a suggestion from John Maindonald.
trellis.device
, xyplot
,
Lattice
str(simpleTheme(pch = 16)) dotplot(variety ~ yield | site, data = barley, groups = year, auto.key = list(space = "right"), par.settings = simpleTheme(pch = 16), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6))
str(simpleTheme(pch = 16)) dotplot(variety ~ yield | site, data = barley, groups = year, auto.key = list(space = "right"), par.settings = simpleTheme(pch = 16), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6))
Functions to handle settings used by lattice. Their main purpose is to make code maintainance easier, and users normally should not need to use these functions. However, fine control at this level maybe useful in certain cases.
lattice.options(...) lattice.getOption(name)
lattice.options(...) lattice.getOption(name)
name |
character giving the name of a setting |
... |
new options can be defined, or existing ones modified, using one or
more arguments of the form |
These functions are modeled on options
and getOption
,
and behave similarly for the most part. Some of the available
components are documented here, but not all. The purpose of the ones
not documented are either fairly obvious, or not of interest to the
end-user.
panel.error
A function, or NULL
. If the former, every call to the
panel function will be wrapped inside tryCatch
with
the specified function as an error handler. The default is to use
the panel.error
function. This prevents the plot
from failing due to errors in a single panel, and leaving the grid
operations in an unmanageable state. If set to NULL
,
errors in panel functions will not be caught using
tryCatch
.
save.object
Logical flag indicating whether a "trellis"
object should
be saved when plotted for subsequent retrieval and further
manipulation. Defaults to TRUE
.
layout.widths
, layout.heights
Controls details
of the default space allocation in the grid layout created in the
course of plotting a "trellis"
object. Each named
component is a list of arguments to the grid function
unit
(x
, units
, and optionally
data
).
Usually not of interest to the end-user, who should instead use
the similiarly named component in the graphical settings,
modifiable using trellis.par.set
.
drop.unused.levels
A list of two components named
cond
and data
, both logical flags. The flags
indicate whether the unused levels of factors (conditioning
variables and primary variables respectively) will be dropped,
which is usually relevant when a subsetting operation is performed
or an 'interaction' is created. See xyplot
for more
details. Note that this does not control dropping of levels of
the 'groups' argument.
legend.bbox
A character string, either "full"
or "panel"
. This
determines the interpretation of x
and y
when
space="inside"
in key
(determining the legend; see
xyplot
): either the full figure region ('"full"'),
or just the region that bounds the panels and strips ('"panel"').
default.args
A list giving default values for various
standard arguments: as.table
, auto.key
,
aspect
, between
, grid
, skip
,
strip
, xscale.components
, yscale.components
,
and axis
.
highlight.gpar
A list giving arguments to
gpar
used to highlight a viewport chosen using
trellis.focus
.
banking
The banking function. See
banking
.
axis.padding
List with components named
"numeric"
and "factor"
, both scalar numbers.
Panel limits are extended by this amount, to provide padding
for numeric and factor scales respectively. The value for
numeric is multiplicative, whereas factor is additive.
skip.boundary.labels
Numeric scalar between 0 and 1. Tick marks that are too close to the limits are not drawn unless explicitly requested. The limits are contracted by this proportion, and anything outside is skipped.
interaction.sep
The separator for creating
interactions with the extended formula interface (see
xyplot
).
optimize.grid
Logical flag, FALSE
by
default. Complicated grid unit calculations can be slow. Sometimes
these can be optimized at the cost of potential loss of
accuracy. This option controls whether such optimization should be
applied.
axis.units
List determining default units for axis components. Should not be of interest to the end-user.
In addition, there is an option for the default prepanel and panel
function for each high-level function; e.g., panel.xyplot
and
prepanel.default.xyplot
for xyplot
. The options
for the others have similarly patterned names.
lattice.getOption
returns the value of a single component,
whereas lattice.options
always returns a list with one or more
named components. When changing the values of components, the old
values of the modified components are returned by
lattice.options
. If called without any arguments, the full
list is returned.
Deepayan Sarkar [email protected]
options
, trellis.device
,
trellis.par.get
, Lattice
names(lattice.options()) str(lattice.getOption("layout.widths"), max.level = 2) ## Not run: ## change default settings for subsequent plots lattice.options(default.args = list(as.table = TRUE, grid = TRUE, auto.key = TRUE)) ## End(Not run)
names(lattice.options()) str(lattice.getOption("layout.widths"), max.level = 2) ## Not run: ## change default settings for subsequent plots lattice.options(default.args = list(as.table = TRUE, grid = TRUE, auto.key = TRUE)) ## End(Not run)
The print
and plot
methods produce a graph from a
"trellis"
object. The print
method is necessary for
automatic plotting. plot
method is essentially
an alias, provided for convenience. The summary
method
gives a textual summary of the object. dim
and dimnames
describe the cross-tabulation induced by conditioning.
panel.error
is the default handler used when an error occurs
while executing the panel function.
## S3 method for class 'trellis' plot(x, position, split, more = FALSE, newpage = TRUE, packet.panel = packet.panel.default, draw.in = NULL, panel.height = lattice.getOption("layout.heights")$panel, panel.width = lattice.getOption("layout.widths")$panel, save.object = lattice.getOption("save.object"), panel.error = lattice.getOption("panel.error"), prefix, ...) ## S3 method for class 'trellis' print(x, ...) ## S3 method for class 'trellis' summary(object, ...) ## S3 method for class 'trellis' dim(x) ## S3 method for class 'trellis' dimnames(x) panel.error(e)
## S3 method for class 'trellis' plot(x, position, split, more = FALSE, newpage = TRUE, packet.panel = packet.panel.default, draw.in = NULL, panel.height = lattice.getOption("layout.heights")$panel, panel.width = lattice.getOption("layout.widths")$panel, save.object = lattice.getOption("save.object"), panel.error = lattice.getOption("panel.error"), prefix, ...) ## S3 method for class 'trellis' print(x, ...) ## S3 method for class 'trellis' summary(object, ...) ## S3 method for class 'trellis' dim(x) ## S3 method for class 'trellis' dimnames(x) panel.error(e)
x , object
|
an object of class |
position |
a vector of 4 numbers, typically c(xmin, ymin, xmax, ymax) that give the lower-left and upper-right corners of a rectangle in which the Trellis plot of x is to be positioned. The coordinate system for this rectangle is [0-1] in both the x and y directions. |
split |
a vector of 4 integers, c(x,y,nx,ny) , that says to position the current plot at the x,y position in a regular array of nx by ny plots. (Note: this has origin at top left) |
more |
A logical specifying whether more plots will follow on this page. |
newpage |
A logical specifying whether the plot should be on a new page. This option is specific to lattice, and is useful for including lattice plots in an arbitrary grid viewport (see the details section). |
packet.panel |
a function that determines which packet (data
subset) is plotted in which panel. Panels are always drawn in an
order such that columns vary the fastest, then rows and then pages.
This function determines, given the column, row and page and other
relevant information, the packet (if any) which should be used in
that panel. By default, the association is determnined by matching
panel order with packet order, which is determined by varying the
first conditioning variable the fastest, then the second, and so
on. This association rule is encoded in the default, namely the
function |
draw.in |
An optional (grid) viewport (used as the |
panel.width , panel.height
|
lists with 2 components, that should be valid Note that this option should not be used in conjunction with
non-default values of the |
save.object |
logical, specifying whether the object being printed is to be
saved. The last object thus saved can be subsequently retrieved.
This is an experimental feature that should allow access to a
panel's data after the plot is done, making it possible to enhance
the plot after the fact. This also allows the user to invoke the
|
panel.error |
a function, or a character string naming a function, that is to be
executed when an error occurs during the execution of the panel
function. The error is caught (using Normal error recovery and debugging tools are unhelpful when
|
prefix |
A character string acting as a prefix identifying the plot of a
|
e |
an error condition caught by |
... |
extra arguments, ignored by the |
This is the default print method for objects of class
"trellis"
, produced by calls to functions like xyplot
,
bwplot
etc. It is usually called automatically when a trellis
object is produced. It can also be called explicitly to control plot
positioning by means of the arguments split
and
position
.
When newpage = FALSE
, the current grid viewport is treated as
the plotting area, making it possible to embed a Lattice plot inside
an arbitrary grid viewport. The draw.in
argument provides an
alternative mechanism that may be simpler to use.
The print method uses the information in x
(the object to be
printed) to produce a display using the Grid graphics engine. At the
heart of the plot is a grid layout, of which the entries of most
interest to the user are the ones containing the display panels.
Unlike in older versions of Lattice (and Grid), the grid display tree
is retained after the plot is produced, making it possible to access
individual viewport locations and make additions to the plot. For
more details and a lattice level interface to these viewports, see
trellis.focus
.
Unlike S-PLUS, trying to position a multipage display (using
position
and/or split
) will mess things up.
Deepayan Sarkar [email protected]
Lattice
, unit
,
update.trellis
, trellis.focus
,
packet.panel.default
p11 <- histogram( ~ height | voice.part, data = singer, xlab="Height") p12 <- densityplot( ~ height | voice.part, data = singer, xlab = "Height") p2 <- histogram( ~ height, data = singer, xlab = "Height") ## simple positioning by split print(p11, split=c(1,1,1,2), more=TRUE) print(p2, split=c(1,2,1,2)) ## Combining split and position: print(p11, position = c(0,0,.75,.75), split=c(1,1,1,2), more=TRUE) print(p12, position = c(0,0,.75,.75), split=c(1,2,1,2), more=TRUE) print(p2, position = c(.5,.75,1,1), more=FALSE) ## Using seekViewport ## repeat same plot, with different polynomial fits in each panel xyplot(Armed.Forces ~ Year, longley, index.cond = list(rep(1, 6)), layout = c(3, 2), panel = function(x, y, ...) { panel.xyplot(x, y, ...) fm <- lm(y ~ poly(x, panel.number())) llines(x, predict(fm)) }) ## Not run: grid::seekViewport(trellis.vpname("panel", 1, 1)) cat("Click somewhere inside the first panel:\n") ltext(grid::grid.locator(), lab = "linear") ## End(Not run) grid::seekViewport(trellis.vpname("panel", 1, 1)) grid::grid.text("linear") grid::seekViewport(trellis.vpname("panel", 2, 1)) grid::grid.text("quadratic") grid::seekViewport(trellis.vpname("panel", 3, 1)) grid::grid.text("cubic") grid::seekViewport(trellis.vpname("panel", 1, 2)) grid::grid.text("degree 4") grid::seekViewport(trellis.vpname("panel", 2, 2)) grid::grid.text("degree 5") grid::seekViewport(trellis.vpname("panel", 3, 2)) grid::grid.text("degree 6")
p11 <- histogram( ~ height | voice.part, data = singer, xlab="Height") p12 <- densityplot( ~ height | voice.part, data = singer, xlab = "Height") p2 <- histogram( ~ height, data = singer, xlab = "Height") ## simple positioning by split print(p11, split=c(1,1,1,2), more=TRUE) print(p2, split=c(1,2,1,2)) ## Combining split and position: print(p11, position = c(0,0,.75,.75), split=c(1,1,1,2), more=TRUE) print(p12, position = c(0,0,.75,.75), split=c(1,2,1,2), more=TRUE) print(p2, position = c(.5,.75,1,1), more=FALSE) ## Using seekViewport ## repeat same plot, with different polynomial fits in each panel xyplot(Armed.Forces ~ Year, longley, index.cond = list(rep(1, 6)), layout = c(3, 2), panel = function(x, y, ...) { panel.xyplot(x, y, ...) fm <- lm(y ~ poly(x, panel.number())) llines(x, predict(fm)) }) ## Not run: grid::seekViewport(trellis.vpname("panel", 1, 1)) cat("Click somewhere inside the first panel:\n") ltext(grid::grid.locator(), lab = "linear") ## End(Not run) grid::seekViewport(trellis.vpname("panel", 1, 1)) grid::grid.text("linear") grid::seekViewport(trellis.vpname("panel", 2, 1)) grid::grid.text("quadratic") grid::seekViewport(trellis.vpname("panel", 3, 1)) grid::grid.text("cubic") grid::seekViewport(trellis.vpname("panel", 1, 2)) grid::grid.text("degree 4") grid::seekViewport(trellis.vpname("panel", 2, 2)) grid::grid.text("degree 5") grid::seekViewport(trellis.vpname("panel", 3, 2)) grid::grid.text("degree 6")
Update method for objects of class "trellis"
, and a way to retrieve
the last printed trellis object (that was saved).
## S3 method for class 'trellis' update(object, panel, aspect, as.table, between, key, auto.key, legend, layout, main, page, par.strip.text, prepanel, scales, skip, strip, strip.left, sub, xlab, ylab, xlab.top, ylab.right, xlim, ylim, xscale.components, yscale.components, axis, par.settings, plot.args, lattice.options, index.cond, perm.cond, ...) ## S3 method for class 'trellis' t(x) ## S3 method for class 'trellis' x[i, j, ..., drop = FALSE] trellis.last.object(..., prefix)
## S3 method for class 'trellis' update(object, panel, aspect, as.table, between, key, auto.key, legend, layout, main, page, par.strip.text, prepanel, scales, skip, strip, strip.left, sub, xlab, ylab, xlab.top, ylab.right, xlim, ylim, xscale.components, yscale.components, axis, par.settings, plot.args, lattice.options, index.cond, perm.cond, ...) ## S3 method for class 'trellis' t(x) ## S3 method for class 'trellis' x[i, j, ..., drop = FALSE] trellis.last.object(..., prefix)
object , x
|
The object to be updated, of class |
i , j
|
indices to be used. Names are not currently allowed. |
drop |
logical, whether dimensions with only one level are to be dropped.
Currently ignored, behaves as if it were |
panel , aspect , as.table , between , key , auto.key , legend , layout , main , page , par.strip.text , prepanel , scales , skip , strip , strip.left , sub , xlab , ylab , xlab.top , ylab.right , xlim , ylim , xscale.components , yscale.components , axis , par.settings , plot.args , lattice.options , index.cond , perm.cond , ...
|
arguments that will be used to update |
prefix |
A character string acting as a prefix identifying the plot of a
|
All high level lattice functions such as xyplot
produce an
object of (S3) class "trellis"
, which is usually displayed by its
print
method. However, the object itself can be manipulated and
modified to a large extent using the update
method, and then
re-displayed as needed.
Most arguments to high level functions can also be supplied to the
update
method as well, with some exceptions. Generally
speaking, anything that would needs to change the data within each
panel is a no-no (this includes the formula, data, groups,
subscripts
and subset
). Everything else is technically game,
though might not be implemented yet. If you find something missing
that you wish to have, feel free to make a request.
Not all arguments accepted by a Lattice function are processed by
update
, but the ones listed above should work. The purpose of
these arguments are described in the help page for
xyplot
. Any other argument is added to the list of
arguments to be passed to the panel
function. Because of their
somewhat special nature, updates to objects produced by cloud
and wireframe
do not work very well yet.
The "["
method is a convenient shortcut for updating
index.cond
. The t
method is a convenient shortcut for
updating perm.cond
in the special (but frequent) case where
there are exactly two conditioning variables, when it has the effect
of switching (‘transposing’) their order.
The print method for "trellis"
objects optionally saves the
object after printing it. If this feature is enabled,
trellis.last.object
can retrieve it. By default, the last
object plotted is retrieved, but if multiple objects are plotted on
the current page, then others can be retrieved using the appropriate
prefix
argument. If trellis.last.object
is
called with arguments, these are used to update the retrieved object
before returning it.
An object of class trellis
, by default plotted by
print.trellis
. trellis.last.object
returns
NULL
is no saved object is available.
Deepayan Sarkar [email protected]
trellis.object
, Lattice
,
xyplot
spots <- by(sunspots, gl(235, 12, labels = 1749:1983), mean) old.options <- lattice.options(save.object = TRUE) xyplot(spots ~ 1749:1983, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Average Yearly Sunspots") update(trellis.last.object(), aspect = "xy") trellis.last.object(xlab = "Year") lattice.options(old.options)
spots <- by(sunspots, gl(235, 12, labels = 1749:1983), mean) old.options <- lattice.options(save.object = TRUE) xyplot(spots ~ 1749:1983, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Average Yearly Sunspots") update(trellis.last.object(), aspect = "xy") trellis.last.object(xlab = "Year") lattice.options(old.options)
Functions to handle shingles
shingle(x, intervals=sort(unique(x))) equal.count(x, ...) as.shingle(x) is.shingle(x) ## S3 method for class 'shingle' plot(x, panel, xlab, ylab, ...) ## S3 method for class 'shingle' print(x, showValues = TRUE, ...) ## S3 method for class 'shingleLevel' as.character(x, ...) ## S3 method for class 'shingleLevel' print(x, ...) ## S3 method for class 'shingle' summary(object, showValues = FALSE, ...) ## S3 method for class 'shingle' x[subset, drop = FALSE] as.factorOrShingle(x, subset, drop)
shingle(x, intervals=sort(unique(x))) equal.count(x, ...) as.shingle(x) is.shingle(x) ## S3 method for class 'shingle' plot(x, panel, xlab, ylab, ...) ## S3 method for class 'shingle' print(x, showValues = TRUE, ...) ## S3 method for class 'shingleLevel' as.character(x, ...) ## S3 method for class 'shingleLevel' print(x, ...) ## S3 method for class 'shingle' summary(object, showValues = FALSE, ...) ## S3 method for class 'shingle' x[subset, drop = FALSE] as.factorOrShingle(x, subset, drop)
x |
numeric variable or R object, shingle in |
object |
shingle object to be summarized |
showValues |
logical, whether to print the numeric part. If FALSE, only the intervals are printed |
intervals |
numeric vector or matrix with 2 columns |
subset |
logical vector |
drop |
whether redundant shingle levels are to be dropped |
panel , xlab , ylab
|
standard Trellis arguments (see
|
... |
other arguments, passed down as appropriate. For
example, extra arguments to |
A shingle is a data structure used in Trellis, and is a generalization
of factors to ‘continuous’ variables. It consists of a numeric
vector along with some possibly overlapping intervals. These intervals
are the ‘levels’ of the shingle. The levels
and
nlevels
functions, usually applicable to factors, also work on
shingles. The implementation of shingles is slightly different from
S.
There are print methods for shingles, as well as for printing the
result of levels()
applied to a shingle. For use in labelling,
the as.character
method can be used to convert levels of a
shingle to character strings.
equal.count
converts x
to a shingle using the equal
count algorithm. This is essentially a wrapper around
co.intervals
. All arguments are passed to co.intervals
.
shingle
creates a shingle using the given intervals
. If
intervals
is a vector, these are used to form 0 length
intervals.
as.shingle
returns shingle(x)
if x
is not a
shingle.
is.shingle
tests whether x
is a shingle.
plot.shingle
displays the ranges of shingles via
rectangles. print.shingle
and summary.shingle
describe
the shingle object.
x$intervals
for levels.shingle(x)
,
logical for is.shingle
, an object of class "trellis"
for
plot
(printed by default by print.trellis
), and
an object of class "shingle"
for the others.
Deepayan Sarkar [email protected]
z <- equal.count(rnorm(50)) plot(z) print(z) print(levels(z))
z <- equal.count(rnorm(50)) plot(z) print(z) print(levels(z))
Creates (and optionally draws) a grid frame grob representing a color
key that can be placed in other grid-based plots. Primarily used by
levelplot
when a color key is requested.
draw.colorkey(key, draw = FALSE, vp = NULL)
draw.colorkey(key, draw = FALSE, vp = NULL)
key |
A list determining the key. See documentation for |
draw |
A scalar logical, indicating whether the grob is to be drawn. |
vp |
The viewport in which to draw the grob, if applicable. |
A grid frame object (that inherits from "grob"
)
Deepayan Sarkar [email protected]
Produces (and possibly draws) a Grid frame grob which is a legend (aka key) that can be placed in other Grid plots.
draw.key(key, draw=FALSE, vp=NULL, ...)
draw.key(key, draw=FALSE, vp=NULL, ...)
key |
A list determining the key. See documentation for
|
draw |
logical, whether the grob is to be drawn. |
vp |
viewport |
... |
ignored |
A Grid frame object (that inherits from ‘grob’).
Deepayan Sarkar [email protected]
Calculates false colors from a numeric variable (including factors, using their numeric codes) given a color scheme and breakpoints.
level.colors(x, at, col.regions, colors = TRUE, ...)
level.colors(x, at, col.regions, colors = TRUE, ...)
x |
A numeric or |
at |
A numeric variable of breakpoints defining intervals along
the range of |
col.regions |
A specification of the colors to be assigned to
each interval defined by |
colors |
logical indicating whether colors should be computed
and returned. If |
... |
Extra arguments, ignored. |
If at
has length n, then it defines n-1 intervals. Values of
x
outside the range of at
are not assigned to an
interval, and the return value is NA
for such values.
Colors are chosen by assigning a color to each of the n-1 intervals.
If col.regions
is a palette function (such as
topo.colors
, or the result of calling
colorRampPalette
), it is called with n-1 as an argument
to obtain the colors. Otherwise, if there are exactly n-1 colors in
col.regions
, these get assigned to the intervals. If there are
fewer than n-1 colors, col.regions
gets recycled. If there are
more, a more or less equally spaced (along the length of
col.regions
) subset is chosen.
A vector of the same length as x
. Depending on the
colors
argument, this could be either a vector of colors (in
a form usable by R), or a vector of integer indices representing
which interval the values of x
fall in.
Deepayan Sarkar [email protected]
depth.col <- with(quakes, level.colors(depth, at = do.breaks(range(depth), 30), col.regions = hcl.colors)) xyplot(lat ~ long | equal.count(stations), quakes, strip = strip.custom(var.name = "Stations"), colours = depth.col, panel = function(x, y, colours, subscripts, ...) { panel.xyplot(x, y, pch = 21, col = "transparent", fill = colours[subscripts], ...) })
depth.col <- with(quakes, level.colors(depth, at = do.breaks(range(depth), 30), col.regions = hcl.colors)) xyplot(lat ~ long | equal.count(stations), quakes, strip = strip.custom(var.name = "Stations"), colours = depth.col, panel = function(x, y, colours, subscripts, ...) { panel.xyplot(x, y, pch = 21, col = "transparent", fill = colours[subscripts], ...) })
Combines two or more vectors, possibly of different lengths, producing a data frame with a second column indicating which of these vectors that row came from. This is mostly useful for getting data into a form suitable for use in high level Lattice functions.
make.groups(...)
make.groups(...)
... |
one or more vectors of the same type (coercion is attempted if not), or one or more data frames with similar columns, with possibly differing number of rows. |
When all the input arguments are vectors, a data frame with two columns
data
all the vectors supplied, concatenated
which
factor indicating which vector the corresponding data
value
came from
When all the input arguments are data frames, the result of
rbind
applied to them, along with an additional
which
column as described above.
Deepayan Sarkar [email protected]
sim.dat <- make.groups(uniform = runif(200), exponential = rexp(175), lognormal = rlnorm(150), normal = rnorm(125)) qqmath( ~ data | which, sim.dat, scales = list(y = "free"))
sim.dat <- make.groups(uniform = runif(200), exponential = rexp(175), lognormal = rlnorm(150), normal = rnorm(125)) qqmath( ~ data | which, sim.dat, scales = list(y = "free"))
Simple interface to generate a list appropriate for draw.key
simpleKey(text, points = TRUE, rectangles = FALSE, lines = FALSE, col, cex, alpha, font, fontface, fontfamily, lineheight, ...)
simpleKey(text, points = TRUE, rectangles = FALSE, lines = FALSE, col, cex, alpha, font, fontface, fontfamily, lineheight, ...)
text |
character or expression vector, to be used as labels for levels of the grouping variable |
points |
logical |
rectangles |
logical |
lines |
logical |
col , cex , alpha , font , fontface , fontfamily , lineheight
|
Used as top-level components of the list produced, to be used for
the text labels. Defaults to the values in
|
... |
further arguments added to the list, eventually passed to
|
A lattice plot can include a legend (key) if an appropriate list is
specified as the key
argument to a high level Lattice function
such as xyplot
. This key can be very flexible, but that
flexibility comes at a cost: this list needs to be fairly complicated
even in simple situations. simpleKey
is designed as a useful
shortcut in the common case of a key drawn in conjunction with a
grouping variable, using the default graphical settings.
The simpleKey
function produces a suitable key
argument
using a simpler interface. The resulting list will use the
text
argument as a text component, along with at most one set
each of points, rectangles, and lines. The number of entries (rows)
in the key will be the length of the text
component. The
graphical parameters for the additional components will be derived
from the default graphical settings (wherein lies the simplification,
as otherwise these would have to be provided explicitly).
Calling simpleKey
directly is usually unnecessary. It is most
commonly invoked (during the plotting of the "trellis"
object)
when the auto.key
argument is supplied in a high-level plot
with a groups
argument. In that case, the text
argument
of simpleKey
defaults to levels(groups)
, and the
defaults for the other arguments depend on the relevant high-level
function. Note that these defaults can be overridden by supplying
auto.key
as a list containing the replacement values.
A list that would work as the key
argument to
xyplot
, etc.
Deepayan Sarkar [email protected]
Lattice
, draw.key
,
trellis.par.get
, and
xyplot
, specifically the entry for auto.key
.
strip.default
is the function that draws the strips by default
in Trellis plots. Users can write their own strip functions, but most
commonly this involves calling strip.default
with a slightly
different arguments. strip.custom
provides a convenient way to
obtain new strip functions that differ from strip.default
only
in the default values of certain arguments.
strip.default(which.given, which.panel, var.name, factor.levels, shingle.intervals, strip.names = c(FALSE, TRUE), strip.levels = c(TRUE, FALSE), sep = " : ", style = 1, horizontal = TRUE, bg = trellis.par.get("strip.background")$col[which.given], fg = trellis.par.get("strip.shingle")$col[which.given], par.strip.text = trellis.par.get("add.text")) strip.custom(...)
strip.default(which.given, which.panel, var.name, factor.levels, shingle.intervals, strip.names = c(FALSE, TRUE), strip.levels = c(TRUE, FALSE), sep = " : ", style = 1, horizontal = TRUE, bg = trellis.par.get("strip.background")$col[which.given], fg = trellis.par.get("strip.shingle")$col[which.given], par.strip.text = trellis.par.get("add.text")) strip.custom(...)
which.given |
integer index specifying which of the conditioning variables this strip corresponds to. |
which.panel |
vector of integers as long as the number of
conditioning variables. The contents are indices specifying the
current levels of each of the conditioning variables (thus, this
would be unique for each distinct packet). This is identical to the
return value of |
var.name |
vector of character strings or expressions as long as
the number of conditioning variables. The contents are interpreted
as names for the conditioning variables. Whether they are shown on
the strip depends on the values of |
factor.levels |
vector of character strings or expressions
giving the levels of the conditioning variable currently being
drawn. For more than one conditioning variable, this will vary with
|
shingle.intervals |
if the current strip corresponds to a shingle,
this should be a 2-column matrix giving the levels of the shingle.
(of the form that would be produced by printing
|
strip.names |
a logical vector of length 2, indicating whether or not the name of the conditioning variable that corresponds to the strip being drawn is to be written on the strip. The two components give the values for factors and shingles respectively. This argument is ignored for a factor when |
strip.levels |
a logical vector of length 2, indicating whether or not the level of the conditioning variable that corresponds to the strip being drawn is to be written on the strip. The two components give the values for factors and shingles respectively. |
sep |
character or expression, serving as a separator if the name and level are both to be shown. |
style |
integer, with values 1, 2, 3, 4 and 5 currently
supported, controlling how the current level of a factor is encoded.
Ignored for shingles (actually, when The best way to find out what effect the value of Note that unlike S-PLUS, the default value of |
horizontal |
logical, specifying whether the labels etc should
be horizontal. |
par.strip.text |
list with parameters controlling the text on
each strip, with components |
bg |
strip background color. |
fg |
strip foreground color. |
... |
arguments to be passed on to |
default strip function for trellis functions. Useful
mostly because of the style
argument — non-default styles
are often more informative, especially when the names of the levels
of the factor x
are small. Traditional use is as
strip = function(...) strip.default(style=2,...)
, though
this can be simplified by the use of strip.custom
.
strip.default
is called for its side-effect, which is to draw a
strip appropriate for multi-panel Trellis conditioning plots.
strip.custom
returns a function that is similar to
strip.default
, but with different defaults for the arguments
specified in the call.
Deepayan Sarkar [email protected]
## Traditional use xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = function(..., style) strip.default(..., style = 4)) ## equivalent call using strip.custom xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = strip.custom(style = 4)) xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = FALSE, strip.left = strip.custom(style = 4, horizontal = FALSE))
## Traditional use xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = function(..., style) strip.default(..., style = 4)) ## equivalent call using strip.custom xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = strip.custom(style = 4)) xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = FALSE, strip.left = strip.custom(style = 4, horizontal = FALSE))
This class of objects is returned by high level lattice functions, and
is usually plotted by default by its
print
method.
A trellis object, as returned by high level lattice functions like
xyplot
, is a list with the "class"
attribute set
to "trellis"
. Many of the components of this list are simply
the arguments to the high level function that produced the object.
Among them are: as.table
, layout
, page
,
panel
, prepanel
, main
, sub
,
par.strip.text
, strip
, skip
, xlab
ylab
, par.settings
, lattice.options
and
plot.args
. Some other typical components are:
formula
the Trellis formula used in the call
index.cond
list with index for each of the conditioning variables
perm.cond
permutation of the order of the conditioning variables
aspect.fill
logical, whether aspect
is "fill"
aspect.ratio
numeric, aspect ratio to be used if aspect.fill
is
FALSE
call
call that generated the object.
condlevels
list with levels of the conditioning variables
legend
list describing the legend(s) to be drawn
panel.args
a list as long as the number of panels, each element being a list itself, containing the arguments in named form to be passed to the panel function in that panel.
panel.args.common
a list containing the arguments common to all the panel functions
in name=value
form
x.scales
list describing x-scale, can consist of several other lists,
paralleling panel.args, if x-relation is not "same"
y.scales
list describing y-scale, similar to x.scales
x.between
numeric vector of interpanel x-space
y.between
numeric vector of interpanel y-space
x.limits
numeric vector of length 2 or list, giving x-axis limits
y.limits
similar to x.limits
packet.sizes
array recording the number of observations in each packet
Deepayan Sarkar [email protected]
Lattice
, xyplot
,
print.trellis
The classic Trellis paradigm is to plot the whole object at once, without the possibility of interacting with it afterwards. However, by keeping track of the grid viewports where the panels and strips are drawn, it is possible to go back to them afterwards and enhance them one panel at a time. These functions provide convenient interfaces to help in this. Note that these are still experimental and the exact details may change in future.
panel.identify(x, y = NULL, subscripts = seq_along(x), labels = subscripts, n = length(x), offset = 0.5, threshold = 18, ## in points, roughly 0.25 inches panel.args = trellis.panelArgs(), ...) panel.identify.qqmath(x, distribution, groups, subscripts, labels, panel.args = trellis.panelArgs(), ...) panel.identify.cloud(x, y, z, subscripts, perspective, distance, xlim, ylim, zlim, screen, R.mat, aspect, scales.3d, ..., panel.3d.identify, n = length(subscripts), offset = 0.5, threshold = 18, labels = subscripts, panel.args = trellis.panelArgs()) panel.link.splom(threshold = 18, verbose = getOption("verbose"), ...) panel.brush.splom(threshold = 18, verbose = getOption("verbose"), ...) trellis.vpname(name = c("position", "split", "split.location", "toplevel", "figure", "panel", "strip", "strip.left", "legend", "legend.region", "main", "sub", "xlab", "ylab", "xlab.top", "ylab.right", "page"), column, row, side = c("left", "top", "right", "bottom", "inside"), clip.off = FALSE, prefix) trellis.grobname(name, type = c("", "panel", "strip", "strip.left", "key", "colorkey"), group = 0, which.given = lattice.getStatus("current.which.given", prefix = prefix), which.panel = lattice.getStatus("current.which.panel", prefix = prefix), column = lattice.getStatus("current.focus.column", prefix = prefix), row = lattice.getStatus("current.focus.row", prefix = prefix), prefix = lattice.getStatus("current.prefix")) trellis.focus(name, column, row, side, clip.off, highlight = interactive(), ..., prefix, guess = TRUE, verbose = getOption("verbose")) trellis.switchFocus(name, side, clip.off, highlight, ..., prefix) trellis.unfocus() trellis.panelArgs(x, packet.number)
panel.identify(x, y = NULL, subscripts = seq_along(x), labels = subscripts, n = length(x), offset = 0.5, threshold = 18, ## in points, roughly 0.25 inches panel.args = trellis.panelArgs(), ...) panel.identify.qqmath(x, distribution, groups, subscripts, labels, panel.args = trellis.panelArgs(), ...) panel.identify.cloud(x, y, z, subscripts, perspective, distance, xlim, ylim, zlim, screen, R.mat, aspect, scales.3d, ..., panel.3d.identify, n = length(subscripts), offset = 0.5, threshold = 18, labels = subscripts, panel.args = trellis.panelArgs()) panel.link.splom(threshold = 18, verbose = getOption("verbose"), ...) panel.brush.splom(threshold = 18, verbose = getOption("verbose"), ...) trellis.vpname(name = c("position", "split", "split.location", "toplevel", "figure", "panel", "strip", "strip.left", "legend", "legend.region", "main", "sub", "xlab", "ylab", "xlab.top", "ylab.right", "page"), column, row, side = c("left", "top", "right", "bottom", "inside"), clip.off = FALSE, prefix) trellis.grobname(name, type = c("", "panel", "strip", "strip.left", "key", "colorkey"), group = 0, which.given = lattice.getStatus("current.which.given", prefix = prefix), which.panel = lattice.getStatus("current.which.panel", prefix = prefix), column = lattice.getStatus("current.focus.column", prefix = prefix), row = lattice.getStatus("current.focus.row", prefix = prefix), prefix = lattice.getStatus("current.prefix")) trellis.focus(name, column, row, side, clip.off, highlight = interactive(), ..., prefix, guess = TRUE, verbose = getOption("verbose")) trellis.switchFocus(name, side, clip.off, highlight, ..., prefix) trellis.unfocus() trellis.panelArgs(x, packet.number)
x , y , z
|
variables defining the contents of the panel. In the
case of |
n |
the number of points to identify by default (overridden by a right click) |
subscripts |
an optional vector of integer indices associated with each point. See details below. |
labels |
an optional vector of labels associated with each point. Defaults
to |
distribution , groups
|
typical panel arguments of
|
offset |
the labels are printed either below, above, to the left or to the
right of the identified point, depending on the relative location of
the mouse click. The |
threshold |
threshold in grid's |
panel.args |
list that contains components names |
perspective , distance , xlim , ylim , zlim , screen , R.mat , aspect , scales.3d
|
arguments as passed to |
panel.3d.identify |
the function that is responsible for the actual interaction once the
data rescaling and rotation computations have been done. By
default, an internal function similar to |
name |
A character string indicating which viewport or grob we are looking for. Although these do not necessarily provide access to all viewports and grobs created by a lattice plot, they cover most of the ones that end-users may find interesting.
If When |
column , row
|
integers, indicating position of the panel or strip that should be
assigned focus in the Trellis layout. Rows are usually calculated
from the bottom up, unless the plot was created with
|
guess |
logical. If |
side |
character string, relevant only for legends (i.e., when
|
clip.off |
logical, whether clipping should be off, relevant when |
type |
A character string specifying whether the grob is specific to a particular panel or strip. When |
group |
An integer specifying whether the grob is specific to a particular group within the plot. When |
which.given , which.panel
|
integers, indicating which conditional variable is being represented (within a strip) and the current levels of the conditional variables. When |
prefix |
A character string acting as a prefix identifying the plot of a
Users should not usually need to supply a value for this argument except to interact with an existing plot other than the one plotted last. For |
highlight |
logical, whether the viewport being assigned focus should be
highlighted. For |
packet.number |
integer, which panel to get data from. See
|
verbose |
whether details will be printed |
... |
For |
panel.identify
is similar to identify
. When
called, it waits for the user to identify points (in the panel being
drawn) via mouse clicks. Clicks other than left-clicks terminate the
procedure. Although it is possible to call it as part of the panel
function, it is more typical to use it to identify points after
plotting the whole object, in which case a call to
trellis.focus
first is necessary.
panel.link.splom
is meant for use with splom
,
and requires a panel to be chosen using trellis.focus
before it
is called. Clicking on a point causes that and the corresponding
proections in other pairwise scatter plots to be highlighted.
panel.brush.splom
is a (misnamed) alias for
panel.link.splom
, retained for back-compatibility.
panel.identify.qqmath
is a specialized wrapper meant for use
with the display produced by qqmath
.
panel.identify.qqmath
is a specialized wrapper meant for use
with the display produced by cloud
. It would be unusual
to call them except in a context where default panel function
arguments are available through trellis.panelArgs
(see below).
One way in which panel.identify
etc. are different from
identify
is in how it uses the subscripts
argument. In general, when one identifies points in a panel, one
wants to identify the origin in the data frame used to produce the
plot, and not within that particular panel. This information is
available to the panel function, but only in certain situations. One
way to ensure that subscripts
is available is to specify
subscripts = TRUE
in the high level call such as xyplot
.
If subscripts
is not explicitly specified in the call to
panel.identify
, but is available in panel.args
, then
those values will be used. Otherwise, they default to
seq_along(x)
. In either case, the final return value will be
the subscripts that were marked.
The process of printing (plotting) a Trellis object builds up a grid layout with named viewports which can then be accessed to modify the plot further. While full flexibility can only be obtained by using grid functions directly, a few lattice functions are available for the more common tasks.
trellis.focus
can be used to move to a particular panel or
strip, identified by its position in the array of panels. It can also
be used to focus on the viewport corresponding to one of the labels or
a legend, though such usage would be less useful. The exact
viewport is determined by the name
along with the other
arguments, not all of which are relevant for all names. Note that
when more than one object is plotted on a page, trellis.focus
will always go to the plot that was created last. For more
flexibility, use grid functions directly (see note below).
After a successful call to trellis.focus
, the desired viewport
(typically panel or strip area) will be made the ‘current’
viewport (plotting area), which can then be enhanced by calls to
standard lattice panel functions as well as grid functions.
It is quite common to have the layout of panels chosen when a
"trellis"
object is drawn, and not before then. Information on
the layout (specifically, how many rows and columns, and which packet
belongs in which position in this layout) is retained for the last
"trellis"
object plotted, and is available through
trellis.currentLayout
.
trellis.unfocus
unsets the focus, and makes the top level
viewport the current viewport.
trellis.switchFocus
is a convenience function to switch from
one viewport to another, while preserving the current row
and
column
. Although the rows and columns only make sense for
panels and strips, they would be preserved even when the user switches
to some other viewport (where row/column is irrelevant) and then
switches back.
Once a panel or strip is in focus, trellis.panelArgs
can be
used to retrieve the arguments that were available to the panel
function at that position. In this case, it can be called without
arguments as
trellis.panelArgs()
This usage is also allowed when a "trellis"
object is being
printed, e.g. inside the panel functions or the axis function (but not
inside the prepanel function). trellis.panelArgs
can also
retrieve the panel arguments from any "trellis"
object. Note
that for this usage, one needs to specify the packet.number
(as
described under the panel
entry in xyplot
) and
not the position in the layout, because a layout determines the panel
only after the object has been printed.
It is usually not necessary to call trellis.vpname
and
trellis.grobname
directly. However, they can be useful in
generating appropriate names in a portable way when using grid
functions to interact with the plots directly, as described in the
note below.
panel.identify
returns an integer vector containing the
subscripts of the identified points (see details above). The
equivalent of identify
with pos=TRUE
is not yet
implemented, but can be considered for addition if requested.
trellis.panelArgs
returns a named list of arguments that were
available to the panel function for the chosen panel.
trellis.vpname
and trellis.grobname
return character
strings.
trellis.focus
has a meaningful return value only if it has been
used to focus on a panel interactively, in which case the return value
is a list with components col
and row
giving the column
and row positions respectively of the chosen panel, unless the choice
was cancelled (by a right click), in which case the return value is
NULL
. If click was outside a panel, both col
and
row
are set to 0.
The viewports created by lattice are accessible to the user through
trellis.focus
as described above. Functions from the grid
package can also be used directly. For example,
current.vpTree
can be used to
inspect the current viewport tree and
seekViewport
or
downViewport
can be used to navigate to
these viewports. For such usage, trellis.vpname
and
trellis.grobname
provides a portable way to access the
appropriate viewports and grobs by name.
Deepayan Sarkar [email protected]. Felix
Andrews provided initial implementations of
panel.identify.qqmath
and support for focusing on panels
interctively.
identify
, Lattice
,
print.trellis
, trellis.currentLayout
,
current.vpTree
,
viewports
## Not run: xyplot(1:10 ~ 1:10) trellis.focus("panel", 1, 1) panel.identify() ## End(Not run) xyplot(Petal.Length ~ Sepal.Length | Species, iris, layout = c(2, 2)) Sys.sleep(1) trellis.focus("panel", 1, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 2, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 1, 2) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() ## choosing loess smoothing parameter p <- xyplot(dist ~ speed, cars) panel.loessresid <- function(x = panel.args$x, y = panel.args$y, span, panel.args = trellis.panelArgs()) { fm <- loess(y ~ x, span = span) xgrid <- do.breaks(current.panel.limits()$xlim, 50) ygrid <- predict(fm, newdata = data.frame(x = xgrid)) panel.lines(xgrid, ygrid) pred <- predict(fm) ## center residuals so that they fall inside panel resids <- y - pred + mean(y) fm.resid <- loess.smooth(x, resids, span = span) ##panel.points(x, resids, col = 1, pch = 4) panel.lines(fm.resid, col = 1) } spans <- c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8) update(p, index.cond = list(rep(1, length(spans)))) panel.locs <- trellis.currentLayout() i <- 1 for (row in 1:nrow(panel.locs)) for (column in 1:ncol(panel.locs)) if (panel.locs[row, column] > 0) { trellis.focus("panel", row = row, column = column, highlight = FALSE) panel.loessresid(span = spans[i]) grid::grid.text(paste("span = ", spans[i]), x = 0.25, y = 0.75, default.units = "npc") trellis.unfocus() i <- i + 1 }
## Not run: xyplot(1:10 ~ 1:10) trellis.focus("panel", 1, 1) panel.identify() ## End(Not run) xyplot(Petal.Length ~ Sepal.Length | Species, iris, layout = c(2, 2)) Sys.sleep(1) trellis.focus("panel", 1, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 2, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 1, 2) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() ## choosing loess smoothing parameter p <- xyplot(dist ~ speed, cars) panel.loessresid <- function(x = panel.args$x, y = panel.args$y, span, panel.args = trellis.panelArgs()) { fm <- loess(y ~ x, span = span) xgrid <- do.breaks(current.panel.limits()$xlim, 50) ygrid <- predict(fm, newdata = data.frame(x = xgrid)) panel.lines(xgrid, ygrid) pred <- predict(fm) ## center residuals so that they fall inside panel resids <- y - pred + mean(y) fm.resid <- loess.smooth(x, resids, span = span) ##panel.points(x, resids, col = 1, pch = 4) panel.lines(fm.resid, col = 1) } spans <- c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8) update(p, index.cond = list(rep(1, length(spans)))) panel.locs <- trellis.currentLayout() i <- 1 for (row in 1:nrow(panel.locs)) for (column in 1:ncol(panel.locs)) if (panel.locs[row, column] > 0) { trellis.focus("panel", row = row, column = column, highlight = FALSE) panel.loessresid(span = spans[i]) grid::grid.text(paste("span = ", spans[i]), x = 0.25, y = 0.75, default.units = "npc") trellis.unfocus() i <- i + 1 }
Default panel function for barchart
.
panel.barchart(x, y, box.ratio = 1, box.width, horizontal = TRUE, origin = NULL, reference = TRUE, stack = FALSE, groups = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, ..., identifier = "barchart")
panel.barchart(x, y, box.ratio = 1, box.width, horizontal = TRUE, origin = NULL, reference = TRUE, stack = FALSE, groups = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, ..., identifier = "barchart")
x |
Extent of Bars. By default, bars start at left of panel,
unless |
y |
Horizontal location of bars. Possibly a factor. |
box.ratio |
Ratio of bar width to inter-bar space. |
box.width |
Thickness of bars in absolute units; overrides
|
horizontal |
Logical flag. If FALSE, the plot is ‘transposed’ in the sense
that the behaviours of x and y are switched. x is now the
‘factor’. Interpretation of other arguments change
accordingly. See documentation of |
origin |
The origin for the bars. For grouped displays with
|
reference |
Logical, whether a reference line is to be drawn at the origin. |
stack |
logical, relevant when groups is non-null. If
|
groups |
Optional grouping variable. |
col , border , lty , lwd
|
Graphical parameters for the bars. By default, the trellis parameter
|
... |
Extra arguments will be accepted but ignored. |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
A barchart is drawn in the panel. Note that most arguments controlling
the display can be supplied to the high-level barchart
call
directly.
Deepayan Sarkar [email protected]
barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), origin = 0, ylab = "Barley Yield (bushels/acre)", scales = list(x = list(abbreviate = TRUE, minlength = 5)))
barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), origin = 0, ylab = "Barley Yield (bushels/acre)", scales = list(x = list(abbreviate = TRUE, minlength = 5)))
This is the default panel function for bwplot
.
panel.bwplot(x, y, box.ratio = 1, box.width = box.ratio / (1 + box.ratio), horizontal = TRUE, pch, col, alpha, cex, font, fontfamily, fontface, fill, varwidth = FALSE, notch = FALSE, notch.frac = 0.5, ..., levels.fos, stats = boxplot.stats, coef = 1.5, do.out = TRUE, identifier = "bwplot")
panel.bwplot(x, y, box.ratio = 1, box.width = box.ratio / (1 + box.ratio), horizontal = TRUE, pch, col, alpha, cex, font, fontfamily, fontface, fill, varwidth = FALSE, notch = FALSE, notch.frac = 0.5, ..., levels.fos, stats = boxplot.stats, coef = 1.5, do.out = TRUE, identifier = "bwplot")
x , y
|
numeric vector or factor. Boxplots drawn for each unique value of
|
box.ratio |
ratio of box thickness to inter box space |
box.width |
thickness of box in absolute units; overrides
|
horizontal |
logical. If FALSE, the plot is ‘transposed’ in the sense that
the behaviours of x and y are switched. x is now the
‘factor’. Interpretation of other arguments change
accordingly. See documentation of |
pch , col , alpha , cex , font , fontfamily , fontface
|
graphical
parameters controlling the dot. |
fill |
color to fill the boxplot |
varwidth |
logical. If TRUE, widths of boxplots are proportional to the number of points used in creating it. |
notch |
if |
notch.frac |
numeric in (0,1). When |
stats |
a function, defaulting to |
coef , do.out
|
passed to |
levels.fos |
numeric values corresponding to positions of the factor or shingle variable. For internal use. |
... |
further arguments, ignored. |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates Box and Whisker plot of x
for every level of
y
(or the other way round if horizontal=FALSE
). By
default, the actual boxplot statistics are calculated using
boxplot.stats
. Note that most arguments controlling the
display can be supplied to the high-level bwplot
call directly.
Although the graphical parameters for the dot representing the median
can be controlled by optional arguments, many others can not. These
parameters are obtained from the relevant settings parameters
("box.rectangle"
for the box, "box.umbrella"
for the
whiskers and "plot.symbol"
for the outliers).
Deepayan Sarkar [email protected]
bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", panel = function(...) { panel.grid(v = -1, h = 0) panel.bwplot(...) }, par.settings = list(plot.symbol = list(pch = 4))) bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", notch = TRUE, pch = "|")
bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", panel = function(...) { panel.grid(v = -1, h = 0) panel.bwplot(...) }, par.settings = list(plot.symbol = list(pch = 4))) bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", notch = TRUE, pch = "|")
Default panel functions controlling cloud
and
wireframe
displays.
panel.cloud(x, y, subscripts, z, groups = NULL, perspective = TRUE, distance = if (perspective) 0.2 else 0, xlim, ylim, zlim, panel.3d.cloud = "panel.3dscatter", panel.3d.wireframe = "panel.3dwire", screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), par.box = NULL, xlab, ylab, zlab, xlab.default, ylab.default, zlab.default, scales.3d, proportion = 0.6, wireframe = FALSE, scpos, ..., at, identifier = "cloud") panel.wireframe(...) panel.3dscatter(x, y, z, rot.mat, distance, groups, type = "p", xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, zero.scaled, col, col.point, col.line, lty, lwd, cex, pch, fill, cross, ..., .scale = FALSE, subscripts, identifier = "3dscatter") panel.3dwire(x, y, z, rot.mat = diag(4), distance, shade = FALSE, shade.colors.palette = trellis.par.get("shade.colors")$palette, light.source = c(0, 0, 1000), xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, col = if (shade) "transparent" else "black", lty = 1, lwd = 1, alpha, col.groups = superpose.polygon$col, polynum = 100, ..., .scale = FALSE, drape = FALSE, at, col.regions = regions$col, alpha.regions = regions$alpha, identifier = "3dwire") makeShadePalette(col.regions, ..., min = 0.05, pref = 0.75)
panel.cloud(x, y, subscripts, z, groups = NULL, perspective = TRUE, distance = if (perspective) 0.2 else 0, xlim, ylim, zlim, panel.3d.cloud = "panel.3dscatter", panel.3d.wireframe = "panel.3dwire", screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), par.box = NULL, xlab, ylab, zlab, xlab.default, ylab.default, zlab.default, scales.3d, proportion = 0.6, wireframe = FALSE, scpos, ..., at, identifier = "cloud") panel.wireframe(...) panel.3dscatter(x, y, z, rot.mat, distance, groups, type = "p", xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, zero.scaled, col, col.point, col.line, lty, lwd, cex, pch, fill, cross, ..., .scale = FALSE, subscripts, identifier = "3dscatter") panel.3dwire(x, y, z, rot.mat = diag(4), distance, shade = FALSE, shade.colors.palette = trellis.par.get("shade.colors")$palette, light.source = c(0, 0, 1000), xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, col = if (shade) "transparent" else "black", lty = 1, lwd = 1, alpha, col.groups = superpose.polygon$col, polynum = 100, ..., .scale = FALSE, drape = FALSE, at, col.regions = regions$col, alpha.regions = regions$alpha, identifier = "3dwire") makeShadePalette(col.regions, ..., min = 0.05, pref = 0.75)
x , y , z
|
numeric (or possibly factors) vectors representing the data to be
displayed. The interpretation depends on the context. For
Further, for In |
subscripts |
index specifying which points to draw. The same |
groups |
specification of a grouping variable, passed down from the high level functions. |
perspective |
logical, whether to plot a perspective view. Setting this to
|
distance |
numeric, between 0 and 1, controls amount of perspective. The
distance of the viewing point from the origin (in the transformed
coordinate system) is |
screen |
A list determining the sequence of rotations to be applied to the
data before being plotted. The initial position starts with the
viewing point along the positive z-axis, and the x and y axes in the
usual position. Each component of the list should be named one of
|
R.mat |
initial rotation matrix in homogeneous coordinates, to be applied to
the data before |
par.box |
graphical parameters for box, namely, col, lty and lwd. By default
obtained from the parameter |
xlim , ylim , zlim
|
limits for the respective axes. As with other lattice functions, these could each be a numeric 2-vector or a character vector indicating levels of a factor. |
panel.3d.cloud , panel.3d.wireframe
|
functions that draw the data-driven part of the plot (as opposed to
the bounding box and scales) in Any user-defined custom display would probably want to change these
functions. The intention is to pass as much information to this
function as might be useful (not all of which are used by the
defaults). In particular, these functions can expect arguments
called |
aspect |
aspect as in |
xlab , ylab , zlab
|
Labels, have to be lists. Typically the user will not manipulate
these, but instead control this via arguments to |
xlab.default |
for internal use |
ylab.default |
for internal use |
zlab.default |
for internal use |
scales.3d |
list defining the scales |
proportion |
numeric scalar, gives the length of arrows as a proportion of the sides |
scpos |
A list with three components x, y and z (each a scalar integer),
describing which of the 12 sides of the cube the scales should be
drawn. The defaults should be OK. Valid values are x: 1, 3, 9, 11;
y: 8, 5, 7, 6 and z: 4, 2, 10, 12. (See comments in the source code
of |
wireframe |
logical, indicating whether this is a wireframe plot |
drape |
logical, whether the facets will be colored by height, in a manner
similar to |
at |
When |
col.regions |
vector of colors to be used in conjunction with In |
alpha.regions |
numeric scalar controlling transparency when
|
rot.mat |
4x4 transformation matrix in homogeneous coordinates. This gives the
rotation matrix combining the |
type |
Character vector, specifying type of cloud plot. Can include one or
more of |
xlim.scaled , ylim.scaled , zlim.scaled
|
axis limits (after being scaled to the bounding box) |
zero.scaled |
z-axis location (after being scaled to the bounding box) of the X-Y
plane in the original data scale, to which lines will be dropped (if
within range) from each point when |
cross |
logical, defaults to This is useful for two reasons. It can be set to |
shade |
logical, indicating whether the surface is to be colored using an illumination model with a single light source |
shade.colors.palette |
a function (or the name of one) that is supposed to calculate the color of a facet when shading is being used. Three pieces of information are available to the function: first, the cosine of the angle between the incident light ray and the normal to the surface (representing foreshortening); second, the cosine of half the angle between the reflected ray and the viewing direction (useful for non-Lambertian surfaces); and third, the scaled (average) height of that particular facet with respect to the total plot z-axis limits. All three numbers should be between 0 and 1. The
|
min |
numeric, between 0 and 1, giving a minimum saturation in
|
pref |
numeric, giving a power that is applied to reflectance value before it is used to ‘darken’ the colors. |
light.source |
a 3-vector representing (in cartesian coordinates) the light source. This is relative to the viewing point being (0, 0, 1/distance) (along the positive z-axis), keeping in mind that all observations are bounded within the [-0.5, 0.5] cube |
polynum |
quadrilateral faces are drawn in batches of |
col.groups |
colors for different groups |
col , col.point , col.line , lty , lwd , cex , pch , fill , alpha
|
Graphical parameters. Some other arguments (such as |
... |
other parameters, passed down when appropriate |
.scale |
Logical flag, indicating whether |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
These functions together are responsible for the content drawn inside
each panel in cloud
and wireframe
.
panel.wireframe
is a wrapper to panel.cloud
, which does
the actual work.
panel.cloud
is responsible for drawing the content that does
not depend on the data, namely, the bounding box, the arrows/scales,
etc. At some point, depending on whether wireframe
is TRUE, it
calls either panel.3d.wireframe
or panel.3d.cloud
, which
draws the data-driven part of the plot.
The arguments accepted by these two functions are different, since
they have essentially different purposes. For cloud, the data is
unstructured, and x
, y
and z
are all passed to
the panel.3d.cloud
function. For wireframe, on the other hand,
x
and y
are increasing vectors with unique values,
defining a rectangular grid. z
must be a matrix with
length(x) * length(y)
rows, and as many columns as the number
of groups.
panel.3dscatter
is the default panel.3d.cloud
function.
It has a type
argument similar to panel.xyplot
,
and supports grouped displays. It tries to honour depth ordering,
i.e., points and lines closer to the camera are drawn later,
overplotting more distant ones. (Of course there is no absolute
ordering for line segments, so an ad hoc ordering is used. There is no
hidden point removal.)
panel.3dwire
is the default panel.3d.wireframe
function. It calculates polygons corresponding to the facets one by
one, but waits till it has collected information about polynum
facets, and draws them all at once. This avoids the overhead of
drawing grid.polygon
repeatedly, speeding up the rendering
considerably. If shade = TRUE
, these attempt to color the
surface as being illuminated from a light source at
light.source
. palette.shade
is a simple function that
provides the deafult shading colors
Multiple surfaces are drawn if groups
is non-null in the call
to wireframe
, however, the algorithm is not sophisticated
enough to render intersecting surfaces correctly.
Deepayan Sarkar [email protected]
wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Inferno"), pref = 0.2)) wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Dark Mint"), pref = 0.2)) wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Harmonic"), pref = 0.2))
wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Inferno"), pref = 0.2)) wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Dark Mint"), pref = 0.2)) wireframe(volcano, shade = TRUE, shade.colors.palette = makeShadePalette(hcl.colors(10, "Harmonic"), pref = 0.2))
This is the default panel function for densityplot
.
panel.densityplot(x, darg, plot.points = "jitter", ref = FALSE, groups = NULL, weights = NULL, jitter.amount, type, ..., grid = lattice.getOption("default.args")$grid, identifier = "density")
panel.densityplot(x, darg, plot.points = "jitter", ref = FALSE, groups = NULL, weights = NULL, jitter.amount, type, ..., grid = lattice.getOption("default.args")$grid, identifier = "density")
x |
data points for which density is to be estimated |
darg |
list of arguments to be passed to the |
plot.points |
logical specifying whether or not the data points should be plotted
along with the estimated density. Alternatively, a character string
specifying how the points should be plotted. Meaningful values are
|
ref |
logical, whether to draw x-axis |
groups |
an optional grouping variable. If present,
|
weights |
numeric vector of weights for the density
calculations. If this is specified, the |
jitter.amount |
when |
type |
|
... |
extra graphical parameters. Note that additional
arguments to |
grid |
A logical flag, character string, or list specifying whether and how
a background grid should be drawn. In its general form,
No grid is drawn if |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Deepayan Sarkar [email protected]
Default panel function for dotplot
.
panel.dotplot(x, y, horizontal = TRUE, pch, col, lty, lwd, col.line, levels.fos, groups = NULL, ..., grid = lattice.getOption("default.args")$grid, identifier = "dotplot")
panel.dotplot(x, y, horizontal = TRUE, pch, col, lty, lwd, col.line, levels.fos, groups = NULL, ..., grid = lattice.getOption("default.args")$grid, identifier = "dotplot")
x , y
|
variables to be plotted in the panel. Typically y is the ‘factor’ |
horizontal |
logical. If FALSE, the plot is ‘transposed’
in the sense that the behaviours of x and y are switched. x is now
the ‘factor’. Interpretation of other arguments change
accordingly. See documentation of |
pch , col , lty , lwd , col.line
|
graphical parameters |
levels.fos |
locations where reference lines will be drawn |
groups |
grouping variable (affects graphical parameters) |
... |
extra parameters, passed to |
grid |
A logical flag, or list specifying whether and how a background grid
should be drawn. In its general form |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates (possibly grouped) Dotplot of x
against y
or
vice versa
Deepayan Sarkar [email protected]
This is the default panel function for histogram
.
panel.histogram(x, breaks, equal.widths = TRUE, type = "density", nint = round(log2(length(x)) + 1), alpha, col, border, lty, lwd, ..., identifier = "histogram")
panel.histogram(x, breaks, equal.widths = TRUE, type = "density", nint = round(log2(length(x)) + 1), alpha, col, border, lty, lwd, ..., identifier = "histogram")
x |
The data points for which the histogram is to be drawn |
breaks |
The breakpoints for the histogram |
equal.widths |
logical used when |
type |
Type of histogram, possible values being |
nint |
Number of bins for the histogram |
alpha , col , border , lty , lwd
|
graphical parameters for bars; defaults are obtained from the
|
... |
other arguments, passed to |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Deepayan Sarkar [email protected]
These are the default panel functions for levelplot
and
contourplot
. Also documented is an alternative raster-based
panel function for use with levelplot
.
panel.levelplot(x, y, z, subscripts, at = pretty(z), shrink, labels, label.style = c("mixed", "flat", "align"), contour = FALSE, region = TRUE, col = add.line$col, lty = add.line$lty, lwd = add.line$lwd, border = "transparent", border.lty = 1, border.lwd = 0.1, ..., region.type = c("grid", "contour"), col.regions = regions$col, alpha.regions = regions$alpha, identifier = "levelplot") panel.contourplot(...) panel.levelplot.raster(x, y, z, subscripts, at = pretty(z), ..., col.regions = regions$col, alpha.regions = regions$alpha, interpolate = FALSE, identifier = "levelplot")
panel.levelplot(x, y, z, subscripts, at = pretty(z), shrink, labels, label.style = c("mixed", "flat", "align"), contour = FALSE, region = TRUE, col = add.line$col, lty = add.line$lty, lwd = add.line$lwd, border = "transparent", border.lty = 1, border.lwd = 0.1, ..., region.type = c("grid", "contour"), col.regions = regions$col, alpha.regions = regions$alpha, identifier = "levelplot") panel.contourplot(...) panel.levelplot.raster(x, y, z, subscripts, at = pretty(z), ..., col.regions = regions$col, alpha.regions = regions$alpha, interpolate = FALSE, identifier = "levelplot")
x , y , z
|
Variables defining the plot. |
subscripts |
Integer vector indicating what subset of |
at |
Numeric vector giving breakpoints along the range of
|
shrink |
Either a numeric vector of length 2 (meant to work as both x and y components), or a list with components x and y which are numeric vectors of length 2. This allows the rectangles to be scaled proportional to the z-value. The specification can be made separately for widths (x) and heights (y). The elements of the length 2 numeric vector gives the minimum and maximum proportion of shrinkage (corresponding to min and max of z). |
labels |
Either a logical scalar indicating whether the labels are to be
drawn, or a character or expression vector giving the labels
associated with the
|
label.style |
Controls how label positions and rotation are determined. A value
of |
contour |
A logical flag, specifying whether contour lines should be drawn. |
region |
A logical flag, specifying whether inter-contour regions should be filled with appropriately colored rectangles. |
col , lty , lwd
|
Graphical parameters for contour lines. |
border |
Border color for rectangles used when |
border.lty , border.lwd
|
Graphical parameters for the border |
... |
Extra parameters. |
region.type |
A character string, one of The |
col.regions |
A vector of colors, or a function to produce a vecor of colors, to
be used if |
alpha.regions |
numeric scalar controlling transparency of facets |
interpolate |
logical, passed to |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
The same panel function is used for both levelplot
and
contourplot
(which differ only in default values of some
arguments). panel.contourplot
is a simple wrapper to
panel.levelplot
.
When contour=TRUE
, the contourLines
function is used to
calculate the contour lines.
panel.levelplot.raster
is an alternative panel function that
uses the raster drawing abilities in R 2.11.0 and higher (through
grid.raster
). It has fewer options (e.g., can only
render data on an equispaced grid), but can be more efficient. When
using panel.levelplot.raster
, it may be desirable to render the
color key in the same way. This is possible, but must be done
separately; see levelplot
for details.
Deepayan Sarkar [email protected].
The functionality of region.type = "contour"
is based on code
borrowed from the gridGraphics package, written by Zhijian
(Jason) Wen and Paul Murrell and ported to lattice by Johan Larsson.
levelplot
,
level.colors
,
contourLines
,
filled.contour
require(grid) levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot) suppressWarnings(plot(levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot.raster, interpolate = TRUE))) levelplot(volcano, panel = panel.levelplot.raster) levelplot(volcano, panel = panel.levelplot.raster, col.regions = hcl.colors, cuts = 30, interpolate = TRUE)
require(grid) levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot) suppressWarnings(plot(levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot.raster, interpolate = TRUE))) levelplot(volcano, panel = panel.levelplot.raster) levelplot(volcano, panel = panel.levelplot.raster, col.regions = hcl.colors, cuts = 30, interpolate = TRUE)
This is the default superpanel function for splom
.
panel.pairs(z, panel = lattice.getOption("panel.splom"), lower.panel = panel, upper.panel = panel, diag.panel = "diag.panel.splom", as.matrix = FALSE, groups = NULL, panel.subscripts, subscripts, pscales = 5, prepanel.limits = scale_limits, varnames = colnames(z), varname.col, varname.cex, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.lty, axis.line.lwd, axis.line.alpha, axis.line.tck, ...) diag.panel.splom(x = NULL, varname = NULL, limits, at = NULL, labels = NULL, draw = TRUE, tick.number = 5, varname.col, varname.cex, varname.lineheight, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.alpha, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.alpha, axis.line.lty, axis.line.lwd, axis.line.tck, ...)
panel.pairs(z, panel = lattice.getOption("panel.splom"), lower.panel = panel, upper.panel = panel, diag.panel = "diag.panel.splom", as.matrix = FALSE, groups = NULL, panel.subscripts, subscripts, pscales = 5, prepanel.limits = scale_limits, varnames = colnames(z), varname.col, varname.cex, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.lty, axis.line.lwd, axis.line.alpha, axis.line.tck, ...) diag.panel.splom(x = NULL, varname = NULL, limits, at = NULL, labels = NULL, draw = TRUE, tick.number = 5, varname.col, varname.cex, varname.lineheight, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.alpha, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.alpha, axis.line.lty, axis.line.lwd, axis.line.tck, ...)
z |
The data frame used for the plot. |
panel , lower.panel , upper.panel
|
The panel function used to display each pair of variables. If
specified, In addition to extra arguments not recognized by |
diag.panel |
The panel function used for the diagonals. See arguments to
|
as.matrix |
logical. If |
groups |
Grouping variable, if any |
panel.subscripts |
logical specifying whether the panel function accepts an argument
named |
subscripts |
The indices of the rows of |
pscales |
Controls axis labels, passed down from
These are specifications on a per-variable basis, and used on all
four sides in the diagonal cells used for labelling. Factor
variables are labelled with the factor names. Use |
prepanel.limits |
A function to calculate suitable axis limits given a single argument
Most high-level lattice plots (such as |
x |
data vector corresponding to that row / column (which will be the same for diagonal ‘panels’). |
varname |
(scalar) character string or expression that is to be written centred within the panel |
limits |
numeric of length 2, or, vector of characters, specifying the scale for that panel (used to calculate tick locations when missing) |
at |
locations of tick marks |
labels |
optional labels for tick marks |
draw |
A logical flag specifying whether to draw the tick marks and labels.
If |
tick.number |
A Numeric scalar giving the suggested number of tick marks. |
varnames |
A character or expression vector or giving names to be used for the
variables in |
varname.col |
Color for the variable name in each diagonal
panel. See |
varname.cex |
Size multiplier for the variable name in each diagonal panel. |
varname.lineheight |
Line height for the variable name in each diagonal panel. |
varname.font , varname.fontfamily , varname.fontface
|
Font specification for the variable name in each diagonal panel. |
axis.text.col |
Color for axis label text. |
axis.text.cex |
Size multiplier for axis label text. |
axis.text.font , axis.text.fontfamily , axis.text.fontface
|
Font specification for axis label text. |
axis.text.lineheight |
Line height for axis label text. |
axis.text.alpha |
Alpha-transparency for axis label text. |
axis.line.col |
Color for the axes. |
axis.line.lty |
Line type for the axes. |
axis.line.lwd |
Line width for the axes. |
axis.line.alpha |
Alpha-transparency for the axes. |
axis.line.tck |
A numeric multiplier for the length of tick marks in diagonal panels. |
... |
Further arguments, passed on to |
panel.pairs
is the function that is actually used as the panel
function in a "trellis"
object produced by splom
.
Deepayan Sarkar [email protected]
Cmat <- outer(1:6,1:6, function(i,j) hcl.colors(11)[i+j-1]) ## rainbow(11, start=.12, end=.5)[i+j-1]) splom(~diag(6), as.matrix = TRUE, panel = function(x, y, i, j, ...) { panel.fill(Cmat[i,j]) panel.text(.5,.5, paste("(",i,",",j,")",sep="")) })
Cmat <- outer(1:6,1:6, function(i,j) hcl.colors(11)[i+j-1]) ## rainbow(11, start=.12, end=.5)[i+j-1]) splom(~diag(6), as.matrix = TRUE, panel = function(x, y, i, j, ...) { panel.fill(Cmat[i,j]) panel.text(.5,.5, paste("(",i,",",j,")",sep="")) })
This is the default panel function for parallel
.
panel.parallel(x, y, z, subscripts, groups = NULL, col, lwd, lty, alpha, common.scale = FALSE, lower, upper, ..., horizontal.axis = TRUE, identifier = "parallel")
panel.parallel(x, y, z, subscripts, groups = NULL, col, lwd, lty, alpha, common.scale = FALSE, lower, upper, ..., horizontal.axis = TRUE, identifier = "parallel")
x , y
|
dummy variables, ignored. |
z |
The data frame used for the plot. Each column will be coerced to numeric before being plotted, and an error will be issued if this fails. |
subscripts |
The indices of the rows of |
groups |
An optional grouping variable. If specified, different groups are
distinguished by use of different graphical parameters (i.e., rows
of |
col , lwd , lty , alpha
|
graphical parameters (defaults to the settings for
|
common.scale |
logical, whether a common scale should be used columns of |
lower , upper
|
numeric vectors replicated to be as long as the number of columns in
|
... |
other arguments (ignored) |
horizontal.axis |
logical indicating whether the parallel axes should
be laid out horizontally ( |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Produces parallel coordinate plots, which are easier to
understand from an example than through a verbal description. See
example for parallel
Deepayan Sarkar [email protected]
Inselberg, Alfred (2009) Parallel Coordinates: Visual Multidimensional Geometry and Its Applications, Springer. ISBN: 978-0-387-21507-5.
Inselberg, A. (1985) “The Plane with Parallel Coordinates”, The Visual Computer.
This is the default panel function for qqmath
.
panel.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, ..., tails.n = 0, identifier = "qqmath")
panel.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, ..., tails.n = 0, identifier = "qqmath")
x |
vector (typically numeric, coerced if not) of data values to be used in the panel. |
f.value , distribution
|
Defines how quantiles are calculated. See |
qtype |
The |
groups |
An optional grouping variable. Within each panel, one Q-Q plot is produced for every level of this grouping variable, differentiated by different graphical parameters. |
... |
Further arguments, often graphical parameters, eventually passed on
to |
tails.n |
number of data points to represent exactly on each tail of the
distribution. This reproduces the effect of |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates a Q-Q plot of the data and the theoretical distribution given
by distribution
. Note that most of the arguments controlling
the display can be supplied directly to the high-level qqmath
call.
Deepayan Sarkar [email protected]
set.seed(0) xx <- rt(10000, df = 10) qqmath(~ xx, pch = "+", distribution = qnorm, grid = TRUE, abline = c(0, 1), xlab.top = c("raw", "ppoints(100)", "tails.n = 50"), panel = function(..., f.value) { switch(panel.number(), panel.qqmath(..., f.value = NULL), panel.qqmath(..., f.value = ppoints(100)), panel.qqmath(..., f.value = ppoints(100), tails.n = 50)) }, layout = c(3, 1))[c(1,1,1)]
set.seed(0) xx <- rt(10000, df = 10) qqmath(~ xx, pch = "+", distribution = qnorm, grid = TRUE, abline = c(0, 1), xlab.top = c("raw", "ppoints(100)", "tails.n = 50"), panel = function(..., f.value) { switch(panel.number(), panel.qqmath(..., f.value = NULL), panel.qqmath(..., f.value = ppoints(100)), panel.qqmath(..., f.value = ppoints(100), tails.n = 50)) }, layout = c(3, 1))[c(1,1,1)]
This is the default panel function for stripplot
. Also see
panel.superpose
panel.stripplot(x, y, jitter.data = FALSE, factor = 0.5, amount = NULL, horizontal = TRUE, groups = NULL, ..., grid = lattice.getOption("default.args")$grid, identifier = "stripplot")
panel.stripplot(x, y, jitter.data = FALSE, factor = 0.5, amount = NULL, horizontal = TRUE, groups = NULL, ..., grid = lattice.getOption("default.args")$grid, identifier = "stripplot")
x , y
|
coordinates of points to be plotted |
jitter.data |
whether points should be jittered to avoid
overplotting. The actual jittering is performed inside
|
factor , amount
|
amount of jittering, see |
horizontal |
logical. If FALSE, the plot is ‘transposed’
in the sense that the behaviours of x and y are switched. x is now
the ‘factor’. Interpretation of other arguments change
accordingly. See documentation of |
groups |
optional grouping variable |
... |
additional arguments, passed on to
|
grid |
A logical flag, character string, or list specifying whether and how
a background grid should be drawn. In its general form,
No grid is drawn if |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates stripplot (one dimensional scatterplot) of x
for each level of y
(or vice versa, depending on the value of
horizontal
)
Deepayan Sarkar [email protected]
This is the default panel function for xyplot
. Also see
panel.superpose
. The default panel functions for
splom
and qq
are essentially the same function.
panel.xyplot(x, y, type = "p", groups = NULL, pch, col, col.line, col.symbol, font, fontfamily, fontface, lty, cex, fill, lwd, horizontal = FALSE, ..., smooth = NULL, grid = lattice.getOption("default.args")$grid, abline = NULL, jitter.x = FALSE, jitter.y = FALSE, factor = 0.5, amount = NULL, identifier = "xyplot") panel.splom(..., identifier = "splom") panel.qq(..., identifier = "qq")
panel.xyplot(x, y, type = "p", groups = NULL, pch, col, col.line, col.symbol, font, fontfamily, fontface, lty, cex, fill, lwd, horizontal = FALSE, ..., smooth = NULL, grid = lattice.getOption("default.args")$grid, abline = NULL, jitter.x = FALSE, jitter.y = FALSE, factor = 0.5, amount = NULL, identifier = "xyplot") panel.splom(..., identifier = "splom") panel.qq(..., identifier = "qq")
x , y
|
variables to be plotted in the scatterplot |
type |
character vector controlling how The behaviour if any of the first five are included in Type The remaining values of Type See |
groups |
an optional grouping variable. If present,
|
col , col.line , col.symbol
|
default colours are obtained from |
font , fontface , fontfamily
|
font used when |
pch , lty , cex , lwd , fill
|
other graphical parameters. |
horizontal |
A logical flag controlling the orientation for certain
|
... |
Extra arguments, if any, for |
smooth |
If specificied, indicates the type of smooth to be
added. Can be a character vector containing one or more values from
Normally, smoothing is performed with the |
grid |
A logical flag, character string, or list specifying whether and how
a background grid should be drawn. This provides the same
functionality as Most generally,
No grid is drawn if |
abline |
A numeric vector or more generally a list containing arguments that
are used to call For more flexibility, use |
jitter.x , jitter.y
|
logical, whether the data should be jittered before being plotted. |
factor , amount
|
controls amount of jittering. |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates scatterplot of x
and y
, with various
modifications possible via the type argument. panel.qq
draws a
45 degree line before calling panel.xyplot
.
Note that most of the arguments controlling the display can be
supplied directly to the high-level (e.g. xyplot
) call.
Deepayan Sarkar [email protected]
panel.superpose
,
xyplot
,
splom
types.plain <- c("p", "l", "o", "r", "g", "s", "S", "h", "a", "smooth") types.horiz <- c("s", "S", "h", "a", "smooth") horiz <- rep(c(FALSE, TRUE), c(length(types.plain), length(types.horiz))) types <- c(types.plain, types.horiz) x <- sample(seq(-10, 10, length.out = 15), 30, TRUE) y <- x + 0.25 * (x + 1)^2 + rnorm(length(x), sd = 5) xyplot(y ~ x | gl(1, length(types)), xlab = "type", ylab = list(c("horizontal=TRUE", "horizontal=FALSE"), y = c(1/6, 4/6)), as.table = TRUE, layout = c(5, 3), between = list(y = c(0, 1)), strip = function(...) { panel.fill(trellis.par.get("strip.background")$col[1]) type <- types[panel.number()] grid::grid.text(label = sprintf('"%s"', type), x = 0.5, y = 0.5) grid::grid.rect() }, scales = list(alternating = c(0, 2), tck = c(0, 0.7), draw = FALSE), par.settings = list(layout.widths = list(strip.left = c(1, 0, 0, 0, 0))), panel = function(...) { type <- types[panel.number()] horizontal <- horiz[panel.number()] panel.xyplot(..., type = type, horizontal = horizontal) })[rep(1, length(types))]
types.plain <- c("p", "l", "o", "r", "g", "s", "S", "h", "a", "smooth") types.horiz <- c("s", "S", "h", "a", "smooth") horiz <- rep(c(FALSE, TRUE), c(length(types.plain), length(types.horiz))) types <- c(types.plain, types.horiz) x <- sample(seq(-10, 10, length.out = 15), 30, TRUE) y <- x + 0.25 * (x + 1)^2 + rnorm(length(x), sd = 5) xyplot(y ~ x | gl(1, length(types)), xlab = "type", ylab = list(c("horizontal=TRUE", "horizontal=FALSE"), y = c(1/6, 4/6)), as.table = TRUE, layout = c(5, 3), between = list(y = c(0, 1)), strip = function(...) { panel.fill(trellis.par.get("strip.background")$col[1]) type <- types[panel.number()] grid::grid.text(label = sprintf('"%s"', type), x = 0.5, y = 0.5) grid::grid.rect() }, scales = list(alternating = c(0, 2), tck = c(0, 0.7), draw = FALSE), par.settings = list(layout.widths = list(strip.left = c(1, 0, 0, 0, 0))), panel = function(...) { type <- types[panel.number()] horizontal <- horiz[panel.number()] panel.xyplot(..., type = type, horizontal = horizontal) })[rep(1, length(types))]
These functions are intended to replace common low level traditional graphics functions, primarily for use in panel functions. The originals can not be used (at least not easily) because lattice panel functions need to use grid graphics. Low level drawing functions in grid can be used directly as well, and is often more flexible. These functions are provided for convenience and portability.
lplot.xy(xy, type, pch, lty, col, cex, lwd, font, fontfamily, fontface, col.line, col.symbol, alpha, fill, origin = 0, ..., identifier, name.type) larrows(...) llines(x, ...) lpoints(x, ...) lpolygon(x, ...) lpolypath(x, ...) lrect(...) lsegments(...) ltext(x, ...) ## Default S3 method: larrows(x0 = NULL, y0 = NULL, x1, y1, x2 = NULL, y2 = NULL, angle = 30, code = 2, length = 0.25, unit = "inches", ends = switch(code, "first", "last", "both"), type = "open", col = add.line$col, alpha = add.line$alpha, lty = add.line$lty, lwd = add.line$lwd, fill = NULL, font, fontface, ..., identifier, name.type) ## Default S3 method: llines(x, y = NULL, type = "l", col, alpha, lty, lwd, ..., identifier, name.type) ## Default S3 method: lpoints(x, y = NULL, type = "p", col, pch, alpha, fill, font, fontfamily, fontface, cex, ..., identifier, name.type) ## Default S3 method: lpolygon(x, y = NULL, border = "black", col = "transparent", fill = NULL, font, fontface, ..., rule = c("none", "winding", "evenodd"), identifier, name.type) ## Default S3 method: lpolypath(x, y = NULL, border = "black", col = "transparent", fill = NULL, font, fontface, ..., rule = c("winding", "evenodd"), identifier, name.type) ## Default S3 method: ltext(x, y = NULL, labels = seq_along(x), col, alpha, cex, srt = 0, lineheight, font, fontfamily, fontface, adj = c(0.5, 0.5), pos = NULL, offset = 0.5, ..., identifier, name.type) ## Default S3 method: lrect(xleft, ybottom, xright, ytop, x = (xleft + xright) / 2, y = (ybottom + ytop) / 2, width = xright - xleft, height = ytop - ybottom, col = "transparent", border = "black", lty = 1, lwd = 1, alpha = 1, just = "center", hjust = NULL, vjust = NULL, font, fontface, ..., identifier, name.type) ## Default S3 method: lsegments(x0, y0, x1, y1, x2, y2, col, alpha, lty, lwd, font, fontface, ..., identifier, name.type) panel.arrows(...) panel.lines(...) panel.points(...) panel.polygon(...) panel.rect(...) panel.segments(...) panel.text(...)
lplot.xy(xy, type, pch, lty, col, cex, lwd, font, fontfamily, fontface, col.line, col.symbol, alpha, fill, origin = 0, ..., identifier, name.type) larrows(...) llines(x, ...) lpoints(x, ...) lpolygon(x, ...) lpolypath(x, ...) lrect(...) lsegments(...) ltext(x, ...) ## Default S3 method: larrows(x0 = NULL, y0 = NULL, x1, y1, x2 = NULL, y2 = NULL, angle = 30, code = 2, length = 0.25, unit = "inches", ends = switch(code, "first", "last", "both"), type = "open", col = add.line$col, alpha = add.line$alpha, lty = add.line$lty, lwd = add.line$lwd, fill = NULL, font, fontface, ..., identifier, name.type) ## Default S3 method: llines(x, y = NULL, type = "l", col, alpha, lty, lwd, ..., identifier, name.type) ## Default S3 method: lpoints(x, y = NULL, type = "p", col, pch, alpha, fill, font, fontfamily, fontface, cex, ..., identifier, name.type) ## Default S3 method: lpolygon(x, y = NULL, border = "black", col = "transparent", fill = NULL, font, fontface, ..., rule = c("none", "winding", "evenodd"), identifier, name.type) ## Default S3 method: lpolypath(x, y = NULL, border = "black", col = "transparent", fill = NULL, font, fontface, ..., rule = c("winding", "evenodd"), identifier, name.type) ## Default S3 method: ltext(x, y = NULL, labels = seq_along(x), col, alpha, cex, srt = 0, lineheight, font, fontfamily, fontface, adj = c(0.5, 0.5), pos = NULL, offset = 0.5, ..., identifier, name.type) ## Default S3 method: lrect(xleft, ybottom, xright, ytop, x = (xleft + xright) / 2, y = (ybottom + ytop) / 2, width = xright - xleft, height = ytop - ybottom, col = "transparent", border = "black", lty = 1, lwd = 1, alpha = 1, just = "center", hjust = NULL, vjust = NULL, font, fontface, ..., identifier, name.type) ## Default S3 method: lsegments(x0, y0, x1, y1, x2, y2, col, alpha, lty, lwd, font, fontface, ..., identifier, name.type) panel.arrows(...) panel.lines(...) panel.points(...) panel.polygon(...) panel.rect(...) panel.segments(...) panel.text(...)
x , y , x0 , y0 , x1 , y1 , x2 , y2 , xy
|
locations. |
length , unit
|
determines extent of arrow head. |
angle , code , type , labels , srt , adj , pos , offset
|
arguments
controlling behaviour. See respective base functions for details.
For |
ends |
serves the same function as |
col , alpha , lty , lwd , fill , pch , cex , lineheight , font , fontfamily , fontface , col.line , col.symbol , border
|
graphical
parameters.
|
origin |
for |
xleft , ybottom , xright , ytop
|
see |
width , height , just , hjust , vjust
|
finer control over
rectangles, see |
... |
extra arguments, passed on to lower level functions as appropriate. |
rule |
character string specifying how For polygons, the default rule is |
identifier |
A character string that is prepended to the name of the grob that is created. |
name.type |
A character value indicating whether the name of the grob
should have panel or strip information added to it.
Typically either |
These functions are meant to be grid replacements of the corresponding
base R graphics functions, to allow existing Trellis code to be used
with minimal modification. The functions panel.*
are
essentally identical to the l*
versions, are recommended for
use in new code (as opposed to ported code) as they have more readable
names.
See the documentation of the base functions for usage. Not all arguments are always supported. All these correspond to the default methods only.
There is a new type="H"
option wherever appropriate, which is
similar to type="h"
, but with horizontal lines.
Deepayan Sarkar [email protected]
points
, lines
, rect
,
text
, segments
, arrows
,
Lattice
SD <- 0.1 t <- seq(0, 2*pi, length.out = 50) + rnorm(50, sd = SD) d <- list(x = c(cos(t), NA, rev(0.5 * cos(t))) + rnorm(101, sd = SD), y = c(sin(t), NA, rev(0.5 * sin(t))) + rnorm(101, sd = SD)) ## rectangles xyplot(y ~ x, d, panel = panel.rect, col = 4, alpha = 0.5, width = 0.1, height = 0.1) ## points and lines xyplot(y ~ x, d, panel = panel.lines, col = 4, alpha = 0.5, type = "o", pch = 16) ## polygons and paths (with holes) xyplot(y ~ x, d, panel = panel.polygon, col = 4, alpha = 0.5, rule = "evenodd") ## Example adapted from https://journal.r-project.org/articles/RJ-2012-017/ x <- c(.1, .5, .9, NA, .4, .5, .6, NA, .4, .6, .5) y <- c(.1, .8, .1, NA, .5, .4, .5, NA, .3, .3, .2) d <- data.frame(x = x, y = y) xyplot(y ~ x, data = d, panel = panel.polygon, rule = "none", col = "grey") xyplot(y ~ x, data = d, panel = panel.polypath, rule = "winding", col = "grey") xyplot(y ~ x, data = d, panel = panel.polypath, rule = "evenodd", col = "grey")
SD <- 0.1 t <- seq(0, 2*pi, length.out = 50) + rnorm(50, sd = SD) d <- list(x = c(cos(t), NA, rev(0.5 * cos(t))) + rnorm(101, sd = SD), y = c(sin(t), NA, rev(0.5 * sin(t))) + rnorm(101, sd = SD)) ## rectangles xyplot(y ~ x, d, panel = panel.rect, col = 4, alpha = 0.5, width = 0.1, height = 0.1) ## points and lines xyplot(y ~ x, d, panel = panel.lines, col = 4, alpha = 0.5, type = "o", pch = 16) ## polygons and paths (with holes) xyplot(y ~ x, d, panel = panel.polygon, col = 4, alpha = 0.5, rule = "evenodd") ## Example adapted from https://journal.r-project.org/articles/RJ-2012-017/ x <- c(.1, .5, .9, NA, .4, .5, .6, NA, .4, .6, .5) y <- c(.1, .8, .1, NA, .5, .4, .5, NA, .3, .3, .2) d <- data.frame(x = x, y = y) xyplot(y ~ x, data = d, panel = panel.polygon, rule = "none", col = "grey") xyplot(y ~ x, data = d, panel = panel.polypath, rule = "winding", col = "grey") xyplot(y ~ x, data = d, panel = panel.polypath, rule = "evenodd", col = "grey")
These are predefined panel functions available in lattice for use in constructing new panel functions (often on-the-fly).
panel.abline(a = NULL, b = 0, h = NULL, v = NULL, reg = NULL, coef = NULL, col, col.line, lty, lwd, alpha, type, ..., reference = FALSE, identifier = "abline") panel.refline(...) panel.curve(expr, from, to, n = 101, curve.type = "l", col, lty, lwd, type, ..., identifier = "curve") panel.rug(x = NULL, y = NULL, regular = TRUE, start = if (regular) 0 else 0.97, end = if (regular) 0.03 else 1, x.units = rep("npc", 2), y.units = rep("npc", 2), col, col.line, lty, lwd, alpha, ..., identifier = "rug") panel.average(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.linejoin(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.fill(col, border, ..., identifier = "fill") panel.grid(h=3, v=3, col, col.line, lty, lwd, x, y, ..., identifier = "grid") panel.lmline(x, y, ..., identifier = "lmline") panel.mathdensity(dmath = dnorm, args = list(mean=0, sd=1), n = 50, col, col.line, lwd, lty, type, ..., identifier = "mathdensity")
panel.abline(a = NULL, b = 0, h = NULL, v = NULL, reg = NULL, coef = NULL, col, col.line, lty, lwd, alpha, type, ..., reference = FALSE, identifier = "abline") panel.refline(...) panel.curve(expr, from, to, n = 101, curve.type = "l", col, lty, lwd, type, ..., identifier = "curve") panel.rug(x = NULL, y = NULL, regular = TRUE, start = if (regular) 0 else 0.97, end = if (regular) 0.03 else 1, x.units = rep("npc", 2), y.units = rep("npc", 2), col, col.line, lty, lwd, alpha, ..., identifier = "rug") panel.average(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.linejoin(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.fill(col, border, ..., identifier = "fill") panel.grid(h=3, v=3, col, col.line, lty, lwd, x, y, ..., identifier = "grid") panel.lmline(x, y, ..., identifier = "lmline") panel.mathdensity(dmath = dnorm, args = list(mean=0, sd=1), n = 50, col, col.line, lwd, lty, type, ..., identifier = "mathdensity")
x , y
|
Variables defining the contents of the panel.
In |
a , b
|
Coefficients of the line to be added by
|
coef |
Coefficients of the line to be added as a vector of length 2. |
reg |
A (linear) regression object, with a |
h , v
|
For For If |
reference |
A logical flag determining whether the default
graphical parameters for |
expr |
An expression considered as a function of |
n |
The number of points to use for drawing the curve. |
from , to
|
optional lower and upper x-limits of curve. If missing, limits of current panel are used |
curve.type |
Type of curve ( |
regular |
A logical flag indicating whether the ‘rug’ is to be drawn on the ‘regular’ side (left / bottom) or not (right / top). |
start , end
|
endpoints of rug segments, in normalized parent
coordinates (between 0 and 1). Defaults depend on value of
|
x.units , y.units
|
Character vectors, replicated to be of length two. Specifies the
(grid) units associated with |
col , col.line , lty , lwd , alpha , border
|
Graphical parameters. |
type |
Usually ignored by the panel functions documented here;
the argument is present only to make sure an explicitly specified
|
fun |
The function that will be applied to the subset of
|
horizontal |
A logical flag. If |
dmath |
A vectorized function that produces density values given
a numeric vector named |
args |
A list giving additional arguments to be passed to
|
... |
Further arguments, typically graphical parameters,
passed on to other low-level functions as appropriate. Color can
usually be specified by |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
panel.abline
adds a line of the form y = a + b * x
, or
vertical and/or horizontal lines. Graphical parameters are obtained
from the “add.line” settings by default. panel.refline
is similar, but uses the “reference.line” settings for the
defaults.
panel.grid
draws a reference grid.
panel.curve
adds a curve, similar to what curve
does with add = TRUE
. Graphical parameters for the curve are
obtained from the “add.line” setting.
panel.average
treats one of x
and y
as a factor
(according to the value of horizontal
), calculates fun
applied to the subsets of the other variable determined by each unique
value of the factor, and joins them by a line. Can be used in
conjunction with panel.xyplot
, and more commonly with
panel.superpose
to produce interaction plots.
panel.linejoin
is an alias for panel.average
. It is
retained for back-compatibility, and may go away in future.
panel.mathdensity
plots a (usually theoretical) probability
density function. This can be useful in conjunction with
histogram
and densityplot
to visually assess goodness of
fit (note, however, that qqmath
is more suitable for this).
panel.rug
adds a rug representation of the (marginal)
data to the panel, much like rug
.
panel.lmline(x, y)
is equivalent to
panel.abline(lm(y ~ x))
.
Deepayan Sarkar [email protected]
Lattice, panel.axis
, panel.identify
identify
, trellis.par.set
.
## Interaction Plot bwplot(yield ~ site, barley, groups = year, panel = function(x, y, groups, subscripts, ...) { panel.grid(h = -1, v = 0) panel.stripplot(x, y, ..., jitter.data = TRUE, grid = FALSE, groups = groups, subscripts = subscripts) panel.superpose(x, y, ..., panel.groups = panel.average, grid = FALSE, groups = groups, subscripts = subscripts) }, auto.key = list(points = FALSE, lines = TRUE, columns = 2)) ## Superposing a fitted normal density on a Histogram histogram( ~ height | voice.part, data = singer, layout = c(2, 4), type = "density", border = "transparent", col.line = "grey60", xlab = "Height (inches)", ylab = "Density Histogram\n with Normal Fit", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, args = list(mean = mean(x), sd = sd(x)), ...) } )
## Interaction Plot bwplot(yield ~ site, barley, groups = year, panel = function(x, y, groups, subscripts, ...) { panel.grid(h = -1, v = 0) panel.stripplot(x, y, ..., jitter.data = TRUE, grid = FALSE, groups = groups, subscripts = subscripts) panel.superpose(x, y, ..., panel.groups = panel.average, grid = FALSE, groups = groups, subscripts = subscripts) }, auto.key = list(points = FALSE, lines = TRUE, columns = 2)) ## Superposing a fitted normal density on a Histogram histogram( ~ height | voice.part, data = singer, layout = c(2, 4), type = "density", border = "transparent", col.line = "grey60", xlab = "Height (inches)", ylab = "Density Histogram\n with Normal Fit", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, args = list(mean = mean(x), sd = sd(x)), ...) } )
A predefined panel function that can be used to add a LOESS smooth based on the provided data.
panel.loess(x, y, span = 2/3, degree = 1, family = c("symmetric", "gaussian"), evaluation = 50, lwd, lty, col, col.line, type, horizontal = FALSE, ..., identifier = "loess")
panel.loess(x, y, span = 2/3, degree = 1, family = c("symmetric", "gaussian"), evaluation = 50, lwd, lty, col, col.line, type, horizontal = FALSE, ..., identifier = "loess")
x , y
|
Variables defining the data to be used. |
lwd , lty , col , col.line
|
Graphical parameters for the added
line. |
type |
Ignored. The argument is present only to make sure that
an explicitly specified |
span , degree , family , evaluation
|
Arguments to
|
horizontal |
A logical flag controlling which variable is to be treated as the
predictor (by default |
... |
Extra arguments, passed on to
|
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
The object returned by loess.smooth
.
Deepayan Sarkar [email protected]
Lattice,
loess.smooth
,
prepanel.loess
Useful panel function with qqmath. Draws a line passing through the points (usually) determined by the .25 and .75 quantiles of the sample and the theoretical distribution.
panel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups = NULL, ..., identifier = "qqmathline")
panel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups = NULL, ..., identifier = "qqmathline")
x |
The original sample, possibly reduced to a fewer number of
quantiles, as determined by the |
y |
an alias for |
distribution |
quantile function for reference theoretical distribution. |
probs |
numeric vector of length two, representing probabilities. Corresponding quantile pairs define the line drawn. |
qtype |
the |
groups |
optional grouping variable. If non-null, a line will be drawn for each group. |
... |
other arguments. |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Deepayan Sarkar [email protected]
prepanel.qqmathline
,
qqmath
,
quantile
This function allows the user to place smoothScatter
plots in
lattice graphics.
panel.smoothScatter(x, y = NULL, nbin = 64, cuts = 255, bandwidth, col.regions, colramp, nrpoints = 100, transformation = function(x) x^0.25, pch = ".", cex = 1, col="black", range.x, ..., raster = FALSE, subscripts, identifier = "smoothScatter")
panel.smoothScatter(x, y = NULL, nbin = 64, cuts = 255, bandwidth, col.regions, colramp, nrpoints = 100, transformation = function(x) x^0.25, pch = ".", cex = 1, col="black", range.x, ..., raster = FALSE, subscripts, identifier = "smoothScatter")
x |
Numeric vector containing x-values or n by 2 matrix containing x and y values. |
y |
Numeric vector containing y-values (optional). The length of |
nbin |
Numeric vector of length 1 (for both directions) or 2 (for x and y separately) containing the number of equally spaced grid points for the density estimation. |
cuts |
number of cuts defining the color gradient |
bandwidth |
Numeric vector: the smoothing bandwidth. If missing,
these functions come up with a more or less useful guess. This
parameter then gets passed on to the function
|
col.regions |
character vector of colors, or a function
producing such a vector. Defaults to the |
colramp |
Function accepting an integer |
nrpoints |
Numeric vector of length 1 giving number of points to
be superimposed on the density image. The first |
transformation |
Function that maps the density scale to the color scale. |
pch , cex
|
graphical parameters for the |
range.x |
see |
col |
|
... |
Further arguments that are passed on to
|
raster |
logical; if |
subscripts |
ignored, but necessary for handling of ... in certain situations. Likely to be removed in future. |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
This replicates the display part of the smoothScatter
function by replacing standard graphics calls by grid-compatible ones.
The function is called for its side effects, namely the production of the appropriate plots on a graphics device.
Deepayan Sarkar [email protected]
ddf <- as.data.frame(matrix(rnorm(40000), ncol = 4) + 1.5 * rnorm(10000)) ddf[, c(2,4)] <- (-ddf[, c(2,4)]) xyplot(V1 ~ V2 + V3, ddf, outer = TRUE, panel = panel.smoothScatter, aspect = "iso") ## argument to panel.levelplot xyplot(V1 ~ V2, ddf, panel = panel.smoothScatter, cuts = 10, region.type = "contour") splom(ddf, panel = panel.smoothScatter, nbin = 64, raster = TRUE)
ddf <- as.data.frame(matrix(rnorm(40000), ncol = 4) + 1.5 * rnorm(10000)) ddf[, c(2,4)] <- (-ddf[, c(2,4)]) xyplot(V1 ~ V2 + V3, ddf, outer = TRUE, panel = panel.smoothScatter, aspect = "iso") ## argument to panel.levelplot xyplot(V1 ~ V2, ddf, panel = panel.smoothScatter, cuts = 10, region.type = "contour") splom(ddf, panel = panel.smoothScatter, nbin = 64, raster = TRUE)
A predefined panel function that can be used to add a spline smooth based on the provided data.
panel.spline(x, y, npoints = 101, lwd = plot.line$lwd, lty = plot.line$lty, col, col.line = plot.line$col, type, horizontal = FALSE, ..., keep.data = FALSE, identifier = "spline")
panel.spline(x, y, npoints = 101, lwd = plot.line$lwd, lty = plot.line$lty, col, col.line = plot.line$col, type, horizontal = FALSE, ..., keep.data = FALSE, identifier = "spline")
x , y
|
Variables defining the data to be used. |
npoints |
The number of equally spaced points within the range of the predictor at which the fitted model is evaluated for plotting. |
lwd , lty , col , col.line
|
Graphical parameters for the added
line. |
type |
Ignored. The argument is present only to make sure that
an explicitly specified |
horizontal |
A logical flag controlling which variable is to be treated as the
predictor (by default |
keep.data |
Passed on to |
... |
Extra arguments, passed on to
|
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
The fitted model as returned by smooth.spline
.
Deepayan Sarkar [email protected]
Lattice,
smooth.spline
,
prepanel.spline
These are panel functions for Trellis displays useful when a grouping
variable is specified for use within panels. The x
(and
y
where appropriate) variables are plotted with different
graphical parameters for each distinct value of the grouping variable.
panel.superpose(x, y = NULL, subscripts, groups, panel.groups = "panel.xyplot", ..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha, type = "p", grid = lattice.getOption("default.args")$grid, distribute.type = FALSE) panel.superpose.2(..., distribute.type = TRUE) panel.superpose.plain(..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha)
panel.superpose(x, y = NULL, subscripts, groups, panel.groups = "panel.xyplot", ..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha, type = "p", grid = lattice.getOption("default.args")$grid, distribute.type = FALSE) panel.superpose.2(..., distribute.type = TRUE) panel.superpose.plain(..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha)
x , y
|
Coordinates of the points to be displayed. Usually numeric. |
panel.groups |
The panel function to be used for each subgroup of points. Defaults
to To be able to distinguish between different levels of the
originating group inside |
subscripts |
An integer vector of subscripts giving indices of the |
groups |
A grouping variable. Different graphical parameters will be used to
plot the subsets of observations given by each distinct value of
|
type |
Usually a character vector specifying how each group
should be drawn. Formally, it is passed on to the
The functions If |
grid |
Logical flag specifying whether a background reference
grid should be drawn. See |
col |
A vector color specification. See Details. |
col.line |
A vector color specification. See Details. |
col.symbol |
A vector color specification. See Details. |
pch |
A vector plotting character specification. See Details. |
cex |
A vector size factor specification. See Details. |
fill |
A vector fill color specification. See Details. |
font , fontface , fontfamily
|
A vector color specification. See Details. |
lty |
A vector color specification. See Details. |
lwd |
A vector color specification. See Details. |
alpha |
A vector alpha-transparency specification. See Details. |
... |
Extra arguments. Passed down to |
distribute.type |
logical controlling interpretation of the
|
panel.superpose
divides up the x
(and optionally
y
) variable(s) by the unique values of
groups[subscripts]
, and plots each subset with different
graphical parameters. The graphical parameters (col.symbol
,
pch
, etc.) are usually supplied as suitable atomic vectors, but
can also be lists. When panel.groups
is called for the
i
-th level of groups
, the corresponding element of each
graphical parameter is passed to it. In the list form, the individual
components can themselves be vectors.
The actual plot for each subgroup is created by the
panel.groups
function. With the default panel.groups
,
the col
argument is overridden by col.line
and
col.symbol
for lines and points respectively, which default to
the "superpose.line"
and "superpose.symbol"
settings.
However, col
will still be supplied as an argument to
panel.groups
functions that make use of it, with a default of
"black"
. The defaults of other graphical parameters are also
taken from the "superpose.line"
and "superpose.symbol"
settings as appropriate. The alpha
parameter takes it default
from the "superpose.line"
setting.
panel.superpose
and panel.superpose.2
differ essentially
in how type
is interpreted by default. The default behaviour
in panel.superpose
is the opposite of that in S, which is the
same as that of panel.superpose.2
.
panel.superpose.plain
is the same as panel.superpose
,
except that the default settings for the style arguments are the
same for all groups and are taken from the default plot style.
It is used in xyplot.ts
.
Deepayan Sarkar [email protected]
(panel.superpose.2
originally contributed by Neil Klepeis)
Different functions when used as panel.groups
gives different
types of plots, for example panel.xyplot
,
panel.dotplot
and panel.average
(This can
be used to produce interaction plots).
See Lattice
for an overview of the package, and
xyplot
for common arguments (in particular, the
discussion of the extended formula interface and the groups
argument).
This is a panel function that can create a violin plot. It is
typically used in a high-level call to bwplot
.
panel.violin(x, y, box.ratio = 1, box.width, horizontal = TRUE, alpha, border, lty, lwd, col, varwidth = FALSE, bw, adjust, kernel, window, width, n = 50, from, to, cut, na.rm, ..., identifier = "violin")
panel.violin(x, y, box.ratio = 1, box.width, horizontal = TRUE, alpha, border, lty, lwd, col, varwidth = FALSE, bw, adjust, kernel, window, width, n = 50, from, to, cut, na.rm, ..., identifier = "violin")
x , y
|
numeric vector or factor. Violin plots are drawn for each unique
value of |
box.ratio |
ratio of the thickness of each violin and inter violin space |
box.width |
thickness of the violins in absolute units;
overrides |
horizontal |
logical. If FALSE, the plot is ‘transposed’ in the sense that
the behaviours of |
alpha , border , lty , lwd , col
|
graphical parameters controlling the violin. Defaults are taken
from the |
varwidth |
logical. If |
bw , adjust , kernel , window , width , n , from , to , cut , na.rm
|
arguments to |
... |
arguments passed on to |
identifier |
A character string that is prepended to the names of grobs that are created by this panel function. |
Creates Violin plot of x
for every level of y
. Note that
most arguments controlling the display can be supplied to the
high-level (typically bwplot
) call directly.
Deepayan Sarkar [email protected]
bwplot(voice.part ~ height, singer, panel = function(..., box.ratio) { panel.violin(..., col = "transparent", varwidth = FALSE, box.ratio = box.ratio) panel.bwplot(..., fill = NULL, box.ratio = .1) } )
bwplot(voice.part ~ height, singer, panel = function(..., box.ratio) { panel.violin(..., col = "transparent", varwidth = FALSE, box.ratio = box.ratio) panel.bwplot(..., fill = NULL, box.ratio = .1) } )
These prepanel functions are used as fallback defaults in various high level plot functions in Lattice. These are rarely useful to normal users but may be helpful in developing new displays.
prepanel.default.bwplot(x, y, horizontal, nlevels, origin, stack, ...) prepanel.default.histogram(x, breaks, equal.widths, type, nint, ...) prepanel.default.qq(x, y, ...) prepanel.default.xyplot(x, y, type, subscripts, groups, ...) prepanel.default.cloud(perspective, distance, xlim, ylim, zlim, screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), panel.aspect = 1, ..., zoom = 0.8) prepanel.default.levelplot(x, y, subscripts, ...) prepanel.default.qqmath(x, f.value, distribution, qtype, groups, subscripts, ..., tails.n = 0) prepanel.default.densityplot(x, darg, groups, weights, subscripts, ...) prepanel.default.parallel(x, y, z, ..., horizontal.axis) prepanel.default.splom(z, ...)
prepanel.default.bwplot(x, y, horizontal, nlevels, origin, stack, ...) prepanel.default.histogram(x, breaks, equal.widths, type, nint, ...) prepanel.default.qq(x, y, ...) prepanel.default.xyplot(x, y, type, subscripts, groups, ...) prepanel.default.cloud(perspective, distance, xlim, ylim, zlim, screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), panel.aspect = 1, ..., zoom = 0.8) prepanel.default.levelplot(x, y, subscripts, ...) prepanel.default.qqmath(x, f.value, distribution, qtype, groups, subscripts, ..., tails.n = 0) prepanel.default.densityplot(x, darg, groups, weights, subscripts, ...) prepanel.default.parallel(x, y, z, ..., horizontal.axis) prepanel.default.splom(z, ...)
x , y
|
x and y values, numeric or factor |
horizontal |
logical, applicable when one of the variables is to be treated as categorical (factor or shingle). |
horizontal.axis |
logical indicating whether the
parallel axes should be laid out horizontally ( |
nlevels |
number of levels of such a categorical variable. |
origin , stack
|
for barcharts or the |
breaks , equal.widths , type , nint
|
details of histogram
calculations. |
groups , subscripts
|
See |
weights |
numeric vector of weights for the density
calculations. If this is specified, it is subsetted by
|
perspective , distance , xlim , ylim , zlim , screen , R.mat , aspect , panel.aspect , zoom
|
see |
f.value , distribution , tails.n
|
see |
darg |
list of arguments passed to |
z |
see |
qtype |
type of |
... |
other arguments, usually ignored |
A list with components xlim
, ylim
, dx
and
dy
, and possibly xat
and yat
, the first two being
used to calculate panel axes limits, the last two for banking
computations. The form of these components are described in the help
page for xyplot
.
Deepayan Sarkar [email protected]
xyplot
, banking
, Lattice
.
See documentation of corresponding panel functions for more details
about the arguments.
These are predefined prepanel functions available in Lattice.
prepanel.lmline(x, y, ...) prepanel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups, subscripts, ...) prepanel.loess(x, y, span, degree, family, evaluation, horizontal = FALSE, ...) prepanel.spline(x, y, npoints = 101, horizontal = FALSE, ..., keep.data = FALSE)
prepanel.lmline(x, y, ...) prepanel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups, subscripts, ...) prepanel.loess(x, y, span, degree, family, evaluation, horizontal = FALSE, ...) prepanel.spline(x, y, npoints = 101, horizontal = FALSE, ..., keep.data = FALSE)
x , y
|
x and y values, numeric or factor |
distribution |
quantile function for theoretical
distribution. This is automatically passed in when this is used as a
prepanel function in |
qtype |
type of |
probs |
numeric vector of length two, representing probabilities. If used
with |
span , degree , family , evaluation
|
Arguments controlling the
underlying |
horizontal , npoints
|
See documentation for corresponding panel function. |
keep.data |
Ignored. Present to capture argument of the same
name in |
groups , subscripts
|
See |
... |
Other arguments. These are passed on to other functions
if appropriate (in particular, |
All these prepanel functions compute the limits to be large enough to contain all points as well as the relevant smooth.
In addition, prepanel.lmline
computes the dx
and
dy
such that it reflects the slope of the linear regression
line; for prepanel.qqmathline
, this is the slope of the line
passing through the quantile pairs specified by probs
. For
prepanel.loess
and prepanel.spline
, dx
and
dy
reflect the piecewise slopes of the nonlinear smooth.
usually a list with components xlim
, ylim
, dx
and
dy
, the first two being used to calculate panel axes limits,
the last two for banking computations. The form of these components
are described under xyplot
. There are also several
prepanel functions that serve as the default for high level functions,
see prepanel.default.xyplot
Deepayan Sarkar [email protected]
Lattice, xyplot
, banking
,
panel.loess
, panel.spline
.
Lattice funtions provide control over how the plot axes are annotated
through a common interface. There are two levels of control. The
xscale.components
and yscale.components
arguments can be
functions that determine tick mark locations and labels given a
packet. For more direct control, the axis
argument can be a
function that actually draws the axes. The functions documented here
are the defaults for these arguments. They can additonally be used as
components of user written replacements.
xscale.components.default(lim, packet.number = 0, packet.list = NULL, top = TRUE, ...) yscale.components.default(lim, packet.number = 0, packet.list = NULL, right = TRUE, ...) axis.default(side = c("top", "bottom", "left", "right"), scales, components, as.table, labels = c("default", "yes", "no"), ticks = c("default", "yes", "no"), ..., prefix)
xscale.components.default(lim, packet.number = 0, packet.list = NULL, top = TRUE, ...) yscale.components.default(lim, packet.number = 0, packet.list = NULL, right = TRUE, ...) axis.default(side = c("top", "bottom", "left", "right"), scales, components, as.table, labels = c("default", "yes", "no"), ticks = c("default", "yes", "no"), ..., prefix)
lim |
the range of the data in that packet (data subset corresponding to a combination of levels of the conditioning variable). The range is not necessarily numeric; e.g. for factors, they could be character vectors representing levels, and for the various date-time representations, they could be vectors of length 2 with the corresponding class. |
packet.number |
which packet (counted according to the packet
order, described in |
packet.list |
list, as long as the number of packets, giving all the actual packets. Specifically, each component is the list of arguments given to the panel function when and if that packet is drawn in a panel. (This has not yet been implemented.) |
top , right
|
the value of the |
side |
on which side the axis is to be drawn. The usual partial matching rules apply. |
scales |
the appropriate component of the |
components |
list, similar to those produced by
|
as.table |
the |
labels |
whether labels are to be drawn. By default, the rules
determined by |
ticks |
whether labels are to be drawn. By default, the rules
determined by |
... |
many other arguments may be supplied, and are passed on to other internal functions. |
prefix |
A character string identifying the plot being drawn (see
|
These functions are part of a new API introduced in lattice 0.14 to provide the user more control over how axis annotation is done. While the API has been designed in anticipation of use that was previously unsupported, the implementation has initially focused on reproducing existing capabilities, rather than test new features. At the time of writing, several features are unimplemented. If you require them, please contact the maintainer.
xscale.components.default
and yscale.components.default
return a list of the form suitable as the components
argument
of axis.default
. Valid components in the return value of
xscale.components.default
are:
num.limit
A numeric limit for the box.
bottom
A list with two elements, ticks
and
labels
. ticks
must be a list with components
at
and tck
which give the location and lengths of tick
marks. tck
can be a vector, and will be recycled to be as
long as at
. labels
must be a list with components
at
, labels
, and check.overlap
. at
and
labels
give the location and labels of the tick labels; this
is usually the same as the location of the ticks, but is not
required to be so. check.overlap
is a logical flag
indicating whether overlapping of labels should be avoided by
omitting some of the labels while rendering.
top
This can be a logical flag; if TRUE
,
top
is treated as being the same as bottom
; if
FALSE
, axis annotation for the top axis is omitted.
Alternatively, top
can be a list like bottom
.
Valid components in the return value of
yscale.components.default
are left
and right
.
Their interpretations are analogous to (respectively) the
bottom
and top
components described above.
Deepayan Sarkar [email protected]
Lattice
,
xyplot
,
print.trellis
str(xscale.components.default(c(0, 1))) set.seed(36872) rln <- rlnorm(100) densityplot(rln, scales = list(x = list(log = 2), alternating = 3), xlab = "Simulated lognormal variates", xscale.components = function(...) { ans <- xscale.components.default(...) ans$top <- ans$bottom ans$bottom$labels$labels <- parse(text = ans$bottom$labels$labels) ans$top$labels$labels <- if (require(MASS)) fractions(2^(ans$top$labels$at)) else 2^(ans$top$labels$at) ans }) ## Direct use of axis to show two temperature scales (Celcius and ## Fahrenheit). This does not work for multi-row plots, and doesn't ## do automatic allocation of space F2C <- function(f) 5 * (f - 32) / 9 C2F <- function(c) 32 + 9 * c / 5 axis.CF <- function(side, ...) { ylim <- current.panel.limits()$ylim switch(side, left = { prettyF <- pretty(ylim) labF <- parse(text = sprintf("%s ~ degree * F", prettyF)) panel.axis(side = side, outside = TRUE, at = prettyF, labels = labF) }, right = { prettyC <- pretty(F2C(ylim)) labC <- parse(text = sprintf("%s ~ degree * C", prettyC)) panel.axis(side = side, outside = TRUE, at = C2F(prettyC), labels = labC) }, axis.default(side = side, ...)) } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), axis = axis.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT") ## version using yscale.components yscale.components.CF <- function(...) { ans <- yscale.components.default(...) ans$right <- ans$left ans$left$labels$labels <- parse(text = sprintf("%s ~ degree * F", ans$left$labels$at)) prettyC <- pretty(F2C(ans$num.limit)) ans$right$ticks$at <- C2F(prettyC) ans$right$labels$at <- C2F(prettyC) ans$right$labels$labels <- parse(text = sprintf("%s ~ degree * C", prettyC)) ans } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), yscale.components = yscale.components.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT")
str(xscale.components.default(c(0, 1))) set.seed(36872) rln <- rlnorm(100) densityplot(rln, scales = list(x = list(log = 2), alternating = 3), xlab = "Simulated lognormal variates", xscale.components = function(...) { ans <- xscale.components.default(...) ans$top <- ans$bottom ans$bottom$labels$labels <- parse(text = ans$bottom$labels$labels) ans$top$labels$labels <- if (require(MASS)) fractions(2^(ans$top$labels$at)) else 2^(ans$top$labels$at) ans }) ## Direct use of axis to show two temperature scales (Celcius and ## Fahrenheit). This does not work for multi-row plots, and doesn't ## do automatic allocation of space F2C <- function(f) 5 * (f - 32) / 9 C2F <- function(c) 32 + 9 * c / 5 axis.CF <- function(side, ...) { ylim <- current.panel.limits()$ylim switch(side, left = { prettyF <- pretty(ylim) labF <- parse(text = sprintf("%s ~ degree * F", prettyF)) panel.axis(side = side, outside = TRUE, at = prettyF, labels = labF) }, right = { prettyC <- pretty(F2C(ylim)) labC <- parse(text = sprintf("%s ~ degree * C", prettyC)) panel.axis(side = side, outside = TRUE, at = C2F(prettyC), labels = labC) }, axis.default(side = side, ...)) } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), axis = axis.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT") ## version using yscale.components yscale.components.CF <- function(...) { ans <- yscale.components.default(...) ans$right <- ans$left ans$left$labels$labels <- parse(text = sprintf("%s ~ degree * F", ans$left$labels$at)) prettyC <- pretty(F2C(ans$num.limit)) ans$right$ticks$at <- C2F(prettyC) ans$right$labels$at <- C2F(prettyC) ans$right$labels$labels <- parse(text = sprintf("%s ~ degree * C", prettyC)) ans } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), yscale.components = yscale.components.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT")
Calculates banking slope
banking(dx, dy)
banking(dx, dy)
dx , dy
|
vector of consecutive x, y differences. |
banking
is the banking function used when
aspect = "xy"
in high level Trellis functions. It is usually not
very meaningful except with xyplot
. It considers the
absolute slopes (based on dx
and dy
) and returns a value
which when adjusted by the panel scale limits will make the median of
the above absolute slopes correspond to a 45 degree line.
This function was inspired by the discussion of banking in the
documentation for Trellis Graphics available at Bell Labs' website
(see Lattice
), but is most likely identical to an
algorithm described by Cleveland et al (see below). It is
not clear (to the author) whether this is the algorithm used in
S-PLUS. Alternative banking rules, implemented as a similar function,
can be used as a drop-in replacement by suitably modifying
lattice.options("banking")
.
Deepayan Sarkar [email protected]
Cleveland, William S. and McGill, Marylyn E. and McGill, Robert (1988) “The Shape Parameter of a Two-variable Graph”, Journal of the American Statistical Association, 83, 289–300.
## with and without banking plot <- xyplot(sunspot.year ~ 1700:1988, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Yearly Sunspots") print(plot, position = c(0, .3, 1, .9), more = TRUE) print(update(plot, aspect = "xy", main = "", xlab = "Year"), position = c(0, 0, 1, .3)) ## cut-and-stack plot (see also xyplot.ts) xyplot(sunspot.year ~ time(sunspot.year) | equal.count(time(sunspot.year)), xlab = "", type = "l", aspect = "xy", strip = FALSE, scales = list(x = list(alternating = 2, relation = "sliced")), as.table = TRUE, main = "Yearly Sunspots")
## with and without banking plot <- xyplot(sunspot.year ~ 1700:1988, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Yearly Sunspots") print(plot, position = c(0, .3, 1, .9), more = TRUE) print(update(plot, aspect = "xy", main = "", xlab = "Year"), position = c(0, 0, 1, .3)) ## cut-and-stack plot (see also xyplot.ts) xyplot(sunspot.year ~ time(sunspot.year) | equal.count(time(sunspot.year)), xlab = "", type = "l", aspect = "xy", strip = FALSE, scales = list(x = list(alternating = 2, relation = "sliced")), as.table = TRUE, main = "Yearly Sunspots")
this function is used by high level Lattice functions like
xyplot
to parse the formula argument and evaluate various
components of the data.
latticeParseFormula(model, data, dimension = 2, subset = TRUE, groups = NULL, multiple, outer, subscripts, drop)
latticeParseFormula(model, data, dimension = 2, subset = TRUE, groups = NULL, multiple, outer, subscripts, drop)
model |
the model/formula to be parsed. This can be in either of two
possible forms, one for 2d and one for 3d formulas, determined by
the |
data |
the environment/dataset where the variables in the formula are evaluated. |
dimension |
dimension of the model, see above |
subset |
index for choosing a subset of the data frame |
groups |
the grouping variable, if present |
multiple , outer
|
logicals, determining how a ‘+’ in the y and x components of
the formula are processed. See |
subscripts |
logical, whether subscripts are to be calculated |
drop |
logical or list, similar to the |
returns a list with several components, including left,
right, left.name, right.name, condition
for 2-D, and left,
right.x, right.y, left.name, right.x.name, right.y.name, condition
for 3-D. Other possible components are groups, subscr
Saikat DebRoy, Deepayan Sarkar [email protected]
When a "trellis"
object is plotted, panels are always drawn in
an order such that columns vary the fastest, then rows and then pages.
An optional function can be specified that determines, given the
column, row and page and other relevant information, the packet (if
any) which should be used in that panel. The function documented here
implements the default behaviour, which is to match panel order with
packet order, determined by varying the first conditioning variable
the fastest, then the second, and so on. This matching is performed
after any reordering and/or permutation of the conditioning variables.
packet.panel.default(layout, condlevels, page, row, column, skip, all.pages.skip = TRUE)
packet.panel.default(layout, condlevels, page, row, column, skip, all.pages.skip = TRUE)
layout |
the |
condlevels |
a list of levels of conditioning variables, after relevant permutations and/or reordering of levels |
page , row , column
|
the location of the panel in the coordinate system of pages, rows and columns. |
skip |
the |
all.pages.skip |
whether |
A suitable combination of levels of the conditioning variables in the
form of a numeric vector as long as the number of conditioning
variables, with each element an integer indexing the levels of the
corresponding variable. Specifically, if the return value is
p
, then the i
-th conditioning variable will have level
condlevels[[i]][p[i]]
.
Deepayan Sarkar [email protected]
packet.panel.page <- function(n) { ## returns a function that when used as the 'packet.panel' ## argument in print.trellis plots page number 'n' only function(layout, page, ...) { stopifnot(layout[3] == 1) packet.panel.default(layout = layout, page = n, ...) } } data(mtcars) HP <- equal.count(mtcars$hp, 6) p <- xyplot(mpg ~ disp | HP * factor(cyl), mtcars, layout = c(0, 6, 1)) print(p, packet.panel = packet.panel.page(1)) print(p, packet.panel = packet.panel.page(2))
packet.panel.page <- function(n) { ## returns a function that when used as the 'packet.panel' ## argument in print.trellis plots page number 'n' only function(layout, page, ...) { stopifnot(layout[3] == 1) packet.panel.default(layout = layout, page = n, ...) } } data(mtcars) HP <- equal.count(mtcars$hp, 6) p <- xyplot(mpg ~ disp | HP * factor(cyl), mtcars, layout = c(0, 6, 1)) print(p, packet.panel = packet.panel.page(1)) print(p, packet.panel = packet.panel.page(2))
panel.axis
is the function used by lattice to draw axes. It is
typically not used by users, except those wishing to create advanced
annotation. Keep in mind issues of clipping when trying to use it as
part of the panel function. current.panel.limits
can be used to
retrieve a panel's x and y limits.
panel.axis(side = c("bottom", "left", "top", "right"), at, labels = TRUE, draw.labels = TRUE, check.overlap = FALSE, outside = FALSE, ticks = TRUE, half = !outside, which.half, tck = as.numeric(ticks), rot = if (is.logical(labels)) 0 else c(90, 0), text.col, text.alpha, text.cex, text.font, text.fontfamily, text.fontface, text.lineheight, line.col, line.lty, line.lwd, line.alpha) current.panel.limits(unit = "native")
panel.axis(side = c("bottom", "left", "top", "right"), at, labels = TRUE, draw.labels = TRUE, check.overlap = FALSE, outside = FALSE, ticks = TRUE, half = !outside, which.half, tck = as.numeric(ticks), rot = if (is.logical(labels)) 0 else c(90, 0), text.col, text.alpha, text.cex, text.font, text.fontfamily, text.fontface, text.lineheight, line.col, line.lty, line.lwd, line.alpha) current.panel.limits(unit = "native")
side |
A character string indicating which side axes are to be drawn on. Partial specification is allowed. |
at |
Numeric vector giving location of labels. Can be missing, in which case they are computed from the native coordinates of the active viewport. |
labels |
The labels to go along with |
draw.labels |
A logical indicating whether labels are to be drawn. |
check.overlap |
A logical, whether to check for overlapping of labels. This also has
the effect of removing |
outside |
A logical flag, indicating whether to draw the labels outside the
panel or inside. Note that |
ticks |
Logical flag, whether to draw the tickmarks. |
half |
Logical flag, indicating whether only around half the scales will be
drawn for each side. This is primarily used for axis labeling in
|
which.half |
Character string, either |
tck |
A numeric scalar multiplier for tick length. Can be negative, in which case the ticks point inwards. |
rot |
Rotation angle(s) for labels in degrees. Can be a vector of length 2 for x- and y-axes. |
text.col |
Color for the axis label text. See |
text.alpha |
Alpha-transparency value for the axis label text. |
text.cex |
Size multiplier for the axis label text. |
text.font , text.fontfamily , text.fontface
|
Font for the axis label text. |
text.lineheight |
Line height for the axis label text. |
line.col |
Color for the axis label text. |
line.lty |
Color for the axis. |
line.lwd |
Color for the axis. |
line.alpha |
Alpha-transparency value for the axis. |
unit |
Which grid |
panel.axis
can draw axis tick marks inside or outside a
panel (more precisely, a grid viewport). It honours the (native) axis
scales. Used in panel.pairs
for splom
, as
well as for all the usual axis drawing by the print method for
"trellis"
objects. It can also be used to enhance plots
‘after the fact’ by adding axes.
current.panel.limits
returns a list with components xlim
and ylim
, which are both numeric vectors of length 2, giving
the scales of the current panel (viewport). The values correspond to
the unit system specified by unit
, by default
"native"
.
Deepayan Sarkar [email protected]
Lattice
, xyplot
,
trellis.focus
, unit
Control over lattice plots are provided through a collection of user
specifiable functions that perform various tasks during the plotting.
Not all information is available to all functions. The functions
documented here attempt to provide a consistent interface to access
relevant information from within these user specified functions,
namely those specified as the panel
, strip
and
axis
functions. Note that this information is not available to
the prepanel
function, which is executed prior to the actual
plotting.
current.row(prefix) current.column(prefix) panel.number(prefix) packet.number(prefix) which.packet(prefix) trellis.currentLayout(which = c("packet", "panel"), prefix)
current.row(prefix) current.column(prefix) panel.number(prefix) packet.number(prefix) which.packet(prefix) trellis.currentLayout(which = c("packet", "panel"), prefix)
which |
whether return value (a matrix) should contain panel numbers or packet numbers, which are usually, but not necessarily, the same (see below for details). |
prefix |
A character string acting as a prefix identifying the plot of a
|
trellis.currentLayout
returns a matrix with as many rows and
columns as in the layout of panels in the current plot. Entries in
the matrix are integer indices indicating which packet (or panel; see
below) occupies that position, with 0 indicating the absence of a
panel. current.row
and current.column
return integer
indices specifying which row and column in the layout are currently
active. panel.number
returns an integer counting which panel
is being drawn (starting from 1 for the first panel, a.k.a. the panel
order). packet.number
gives the packet number according to the
packet order, which is determined by varying the first conditioning
variable the fastest, then the second, and so on. which.packet
returns the combination of levels of the conditioning variables in the
form of a numeric vector as long as the number of conditioning
variables, with each element an integer indexing the levels of the
corresponding variable.
The availability of these functions make redundant some features
available in earlier versions of lattice, namely optional arguments
called panel.number
and packet.number
that were made
available to panel
and strip
. If you have written such
functions, it should be enough to replace instances of
panel.number
and packet.number
by the corresponding
function calls. You should also remove panel.number
and
packet.number
from the argument list of your function to avoid
a warning.
If these accessor functions are not enough for your needs, feel free to contact the maintainer and ask for more.
Deepayan Sarkar [email protected]
Convenience function to extract subset of a list. Usually used in creating keys.
Rows(x, which)
Rows(x, which)
x |
list with each member a vector of the same length |
which |
index for members of |
A list similar to x
, with each x[[i]]
replaced by
x[[i]][which]
Deepayan Sarkar [email protected]
These are (related to) the default panel functions for cloud
and wireframe
.
ltransform3dMatrix(screen, R.mat) ltransform3dto3d(x, R.mat, dist)
ltransform3dMatrix(screen, R.mat) ltransform3dto3d(x, R.mat, dist)
x |
|
screen |
list, as described in |
R.mat |
4x4 transformation matrix in homogeneous coordinates |
dist |
controls transformation to account for perspective viewing |
ltransform3dMatrix
and ltransform3dto3d
are utility
functions to help in computation of projections. These functions are
used inside the panel functions for cloud
and
wireframe
. They may be useful in user-defined panel functions
as well.
The first function takes a list of the form of the screen
argument in cloud
and wireframe
and a R.mat
, a
4x4 transformation matrix in homogeneous coordinates, to return a new
4x4 transformation matrix that is the result of applying R.mat
followed by the rotations in screen
. The second function
applies a 4x4 transformation matrix in homogeneous coordinates to a
3xn matrix representing points in 3-D space, and optionally does some
perspective computations. (There has been no testing with non-trivial
transformation matrices, and my knowledge of the homogeneous
coordinate system is very limited, so there may be bugs here.)
Deepayan Sarkar [email protected]
Total yield in bushels per acre for 10 varieties at 6 sites in each of two years.
barley
barley
A data frame with 120 observations on the following 4 variables.
Yield (averaged across three blocks) in bushels/acre.
Factor with levels "Svansota"
, "No. 462"
,
"Manchuria"
, "No. 475"
, "Velvet"
,
"Peatland"
, "Glabron"
, "No. 457"
,
"Wisconsin No. 38"
, "Trebi"
.
Factor with levels 1932
, 1931
Factor with 6 levels: "Grand Rapids"
,
"Duluth"
, "University Farm"
, "Morris"
,
"Crookston"
, "Waseca"
These data are yields in bushels per acre, of 10 varieties of barley grown in 1/40 acre plots at University Farm, St. Paul, and at the five branch experiment stations located at Waseca, Morris, Crookston, Grand Rapids, and Duluth (all in Minnesota). The varieties were grown in three randomized blocks at each of the six stations during 1931 and 1932, different land being used each year of the test.
Immer et al. (1934) present the data for each Year*Site*Variety*Block. The data here is the average yield across the three blocks.
Immer et al. (1934) refer (once) to the experiment as being conducted in 1930 and 1931, then later refer to it (repeatedly) as being conducted in 1931 and 1932. Later authors have continued the confusion.
Cleveland (1993) suggests that the data for the Morris site may have had the years switched.
Documentation contributed by Kevin Wright.
Immer, R. F., H. K. Hayes, and LeRoy Powers. (1934). Statistical Determination of Barley Varietal Adaptation. Journal of the American Society of Agronomy, 26, 403–419.
Wright, Kevin (2013). Revisiting Immer's Barley Data. The American Statistician, 67(3), 129–133.
Cleveland, William S. (1993) Visualizing Data. Hobart Press, Summit, New Jersey.
Fisher, R. A. (1971) The Design of Experiments. Hafner, New York, 9th edition.
immer
in the MASS package for data from the
same experiment
(expressed as total yield for 3 blocks) for a subset of varieties.
# Graphic suggesting the Morris data switched the years 1931 and 1932 # Figure 1.1 from Cleveland dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL)
# Graphic suggesting the Morris data switched the years 1931 and 1932 # Figure 1.1 from Cleveland dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL)
Daily measurements of ozone concentration, wind speed, temperature and solar radiation in New York City from May to September of 1973.
environmental
environmental
A data frame with 111 observations on the following 4 variables.
Average ozone concentration (of hourly measurements) of in parts per billion.
Solar radiation (from 08:00 to 12:00) in langleys.
Maximum daily emperature in degrees Fahrenheit.
Average wind speed (at 07:00 and 10:00) in miles per hour.
Documentation contributed by Kevin Wright.
Bruntz, S. M., W. S. Cleveland, B. Kleiner, and J. L. Warner. (1974). The Dependence of Ambient Ozone on Solar Radiation, Wind, Temperature, and Mixing Height. In Symposium on Atmospheric Diffusion and Air Pollution, pages 125–128. American Meterological Society, Boston.
Cleveland, William S. (1993) Visualizing Data. Hobart Press, Summit, New Jersey.
# Scatter plot matrix with loess lines splom(~environmental, panel=function(x,y){ panel.xyplot(x,y) panel.loess(x,y) } ) # Conditioned plot similar to figure 5.3 from Cleveland attach(environmental) Temperature <- equal.count(temperature, 4, 1/2) Wind <- equal.count(wind, 4, 1/2) xyplot((ozone^(1/3)) ~ radiation | Temperature * Wind, aspect=1, prepanel = function(x, y) prepanel.loess(x, y, span = 1), panel = function(x, y){ panel.grid(h = 2, v = 2) panel.xyplot(x, y, cex = .5) panel.loess(x, y, span = 1) }, xlab = "Solar radiation (langleys)", ylab = "Ozone (cube root ppb)") detach() # Similar display using the coplot function with(environmental,{ coplot((ozone^.33) ~ radiation | temperature * wind, number=c(4,4), panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...), xlab="Solar radiation (langleys)", ylab="Ozone (cube root ppb)") })
# Scatter plot matrix with loess lines splom(~environmental, panel=function(x,y){ panel.xyplot(x,y) panel.loess(x,y) } ) # Conditioned plot similar to figure 5.3 from Cleveland attach(environmental) Temperature <- equal.count(temperature, 4, 1/2) Wind <- equal.count(wind, 4, 1/2) xyplot((ozone^(1/3)) ~ radiation | Temperature * Wind, aspect=1, prepanel = function(x, y) prepanel.loess(x, y, span = 1), panel = function(x, y){ panel.grid(h = 2, v = 2) panel.xyplot(x, y, cex = .5) panel.loess(x, y, span = 1) }, xlab = "Solar radiation (langleys)", ylab = "Ozone (cube root ppb)") detach() # Similar display using the coplot function with(environmental,{ coplot((ozone^.33) ~ radiation | temperature * wind, number=c(4,4), panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...), xlab="Solar radiation (langleys)", ylab="Ozone (cube root ppb)") })
Ethanol fuel was burned in a single-cylinder engine. For various settings of the engine compression and equivalence ratio, the emissions of nitrogen oxides were recorded.
ethanol
ethanol
A data frame with 88 observations on the following 3 variables.
Concentration of nitrogen oxides (NO and NO2) in micrograms/J.
Compression ratio of the engine.
Equivalence ratio–a measure of the richness of the air and ethanol fuel mixture.
Documentation contributed by Kevin Wright.
Brinkman, N.D. (1981) Ethanol Fuel—A Single-Cylinder Engine Study of Efficiency and Exhaust Emissions. SAE transactions, 90, 1410–1424.
Cleveland, William S. (1993) Visualizing Data. Hobart Press, Summit, New Jersey.
## Constructing panel functions on the fly EE <- equal.count(ethanol$E, number=9, overlap=1/4) xyplot(NOx ~ C | EE, data = ethanol, prepanel = function(x, y) prepanel.loess(x, y, span = 1), xlab = "Compression ratio", ylab = "NOx (micrograms/J)", panel = function(x, y) { panel.grid(h=-1, v= 2) panel.xyplot(x, y, grid = FALSE) panel.loess(x, y, span = 1) }, aspect = "xy") # Wireframe loess surface fit. See Figure 4.61 from Cleveland. require(stats) with(ethanol, { eth.lo <- loess(NOx ~ C * E, span = 1/3, parametric = "C", drop.square = "C", family="symmetric") eth.marginal <- list(C = seq(min(C), max(C), length.out = 25), E = seq(min(E), max(E), length.out = 25)) eth.grid <- expand.grid(eth.marginal) eth.fit <- predict(eth.lo, eth.grid) wireframe(eth.fit ~ eth.grid$C * eth.grid$E, shade=TRUE, screen = list(z = 40, x = -60, y=0), distance = .1, xlab = "C", ylab = "E", zlab = "NOx") })
## Constructing panel functions on the fly EE <- equal.count(ethanol$E, number=9, overlap=1/4) xyplot(NOx ~ C | EE, data = ethanol, prepanel = function(x, y) prepanel.loess(x, y, span = 1), xlab = "Compression ratio", ylab = "NOx (micrograms/J)", panel = function(x, y) { panel.grid(h=-1, v= 2) panel.xyplot(x, y, grid = FALSE) panel.loess(x, y, span = 1) }, aspect = "xy") # Wireframe loess surface fit. See Figure 4.61 from Cleveland. require(stats) with(ethanol, { eth.lo <- loess(NOx ~ C * E, span = 1/3, parametric = "C", drop.square = "C", family="symmetric") eth.marginal <- list(C = seq(min(C), max(C), length.out = 25), E = seq(min(E), max(E), length.out = 25)) eth.grid <- expand.grid(eth.marginal) eth.fit <- predict(eth.lo, eth.grid) wireframe(eth.fit ~ eth.grid$C * eth.grid$E, shade=TRUE, screen = list(z = 40, x = -60, y=0), distance = .1, xlab = "C", ylab = "E", zlab = "NOx") })
These data from the Connecticut Tumor Registry present age-adjusted numbers of melanoma skin-cancer incidences per 100,000 people in Connectict for the years from 1936 to 1972.
melanoma
melanoma
A data frame with 37 observations on the following 2 variables.
Years 1936 to 1972.
Rate of melanoma cancer per 100,000 population.
This dataset is not related to the melanoma
dataset in the boot package with the same name.
The S-PLUS 6.2 help for the melanoma data says that the incidence rate is per million, but this is not consistent with data found at the National Cancer Institute (https://www.cancer.gov/).
Documentation contributed by Kevin Wright.
Houghton, A., E. W. Munster, and M. V. Viola. (1978). Increased Incidence of Malignant Melanoma After Peaks of Sunspot Activity. The Lancet, 8, 759–760.
Cleveland, William S. (1993) Visualizing Data. Hobart Press, Summit, New Jersey.
# Time-series plot. Figure 3.64 from Cleveland. xyplot(incidence ~ year, data = melanoma, aspect = "xy", panel = function(x, y) panel.xyplot(x, y, type="o", pch = 16), ylim = c(0, 6), xlab = "Year", ylab = "Incidence")
# Time-series plot. Figure 3.64 from Cleveland. xyplot(incidence ~ year, data = melanoma, aspect = "xy", panel = function(x, y) panel.xyplot(x, y, type="o", pch = 16), ylim = c(0, 6), xlab = "Year", ylab = "Incidence")
Heights in inches of the singers in the New York Choral Society in 1979. The data are grouped according to voice part. The vocal range for each voice part increases in pitch according to the following order: Bass 2, Bass 1, Tenor 2, Tenor 1, Alto 2, Alto 1, Soprano 2, Soprano 1.
singer
singer
A data frame with 235 observations on the following 2 variables.
Height in inches of the singers.
(Unordered) factor with levels "Bass 2
",
"Bass 1
", "Tenor 2
", "Tenor 1
", "Alto 2
",
"Alto 1
", "Soprano 2
", "Soprano 1
".
Documentation contributed by Kevin Wright.
Chambers, J.M., W. S. Cleveland, B. Kleiner, and P. A. Tukey. (1983). Graphical Methods for Data Analysis. Chapman and Hall, New York.
Cleveland, William S. (1993) Visualizing Data. Hobart Press, Summit, New Jersey.
# Separate histogram for each voice part (Figure 1.2 from Cleveland) histogram(~ height | voice.part, data = singer, aspect = 1, layout = c(2, 4), nint = 15, xlab = "Height (inches)") # Quantile-Quantile plot (Figure 2.11 from Cleveland) qqmath(~ height | voice.part, data = singer, aspect = 1, layout = c(2,4), prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.grid() panel.qqmathline(x, ...) panel.qqmath(x, ..., grid = FALSE) }, xlab = "Unit Normal Quantile", ylab="Height (inches)")
# Separate histogram for each voice part (Figure 1.2 from Cleveland) histogram(~ height | voice.part, data = singer, aspect = 1, layout = c(2, 4), nint = 15, xlab = "Height (inches)") # Quantile-Quantile plot (Figure 2.11 from Cleveland) qqmath(~ height | voice.part, data = singer, aspect = 1, layout = c(2,4), prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.grid() panel.qqmathline(x, ...) panel.qqmath(x, ..., grid = FALSE) }, xlab = "Unit Normal Quantile", ylab="Height (inches)")
These datasets record mortality rates across all ages in the USA by cause of death, sex, and rural/urban status, 2011–2013. The two datasets represent the national aggregate rates and the region-wise rates for each administrative region under the Department of Health and Human Services (HHS).
USMortality USRegionalMortality
USMortality USRegionalMortality
USRegionalMortality
is a data frame with 400 observations on
the following 6 variables.
Region
A factor specifying HHS Region. See details.
Status
A factor with levels Rural
and Urban
Sex
A factor with levels Female
and Male
Cause
Cause of death. A factor with levels
Alzheimers
, Cancer
, Cerebrovascular diseases
,
Diabetes
, Flu and pneumonia
, Heart disease
,
Lower respiratory
, Nephritis
, Suicide
, and
Unintentional injuries
Rate
Age-adjusted death rate per 100,000 population
SE
Standard error for the rate
USMortality
is a data frame with 40 observations, containing
the same variables with the exception of Region
.
The region-wise data give estimated rates separately for each of 10 HHS regions. The location of the regional offices and their coverage area, available from https://www.hhs.gov/about/agencies/iea/regional-offices/index.html, is given below.
Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, and Vermont
New Jersey, New York, Puerto Rico, and the Virgin Islands
Delaware, District of Columbia, Maryland, Pennsylvania, Virginia, and West Virginia
Alabama, Florida, Georgia, Kentucky, Mississippi, North Carolina, South Carolina, and Tennessee
Illinois, Indiana, Michigan, Minnesota, Ohio, and Wisconsin
Arkansas, Louisiana, New Mexico, Oklahoma, and Texas
Iowa, Kansas, Missouri, and Nebraska
Colorado, Montana, North Dakota, South Dakota, Utah, and Wyoming
Arizona, California, Hawaii, Nevada, American Samoa, Commonwealth of the Northern Mariana Islands, Federated States of Micronesia, Guam, Marshall Islands, and Republic of Palau
Alaska, Idaho, Oregon, and Washington
Rural Health Reform Policy Research Center. _Exploring Rural and Urban Mortality Differences_, August 2015 Bethesda, MD. https://ruralhealth.und.edu/projects/health-reform-policy-research-center/rural-urban-mortality
dotplot(reorder(Cause, Rate) ~ Rate | Status, data = USMortality, groups = Sex, grid = FALSE, par.settings = simpleTheme(pch = 16), auto.key = list(columns = 2), scales = list(x = list(log = TRUE, equispaced.log = FALSE))) dotplot(reorder(Cause, Rate):Sex ~ Rate | Status, data = USRegionalMortality, groups = Sex, auto.key = FALSE, scales = list(x = list(log = TRUE, equispaced.log = FALSE)))
dotplot(reorder(Cause, Rate) ~ Rate | Status, data = USMortality, groups = Sex, grid = FALSE, par.settings = simpleTheme(pch = 16), auto.key = list(columns = 2), scales = list(x = list(log = TRUE, equispaced.log = FALSE))) dotplot(reorder(Cause, Rate):Sex ~ Rate | Status, data = USRegionalMortality, groups = Sex, auto.key = FALSE, scales = list(x = list(log = TRUE, equispaced.log = FALSE)))
A (hopefully) simpler alternative to trellis.par.get/set
. This
is deprecated, and the same functionality is now available with
trellis.par.set
lset(theme = col.whitebg())
lset(theme = col.whitebg())
theme |
a list decribing how to change the settings of the
current active device. Valid components are those in the list
returned by |
Deepayan Sarkar [email protected]