\name{Devices}
\title{List of Graphical Devices}
\usage{
#ifdef unix
X11(\dots)
#endif
#ifdef windows
windows(\dots)
#endif
%% FIXME:
#ifdef aqua
quartz(\dots)
#endif
postscript(\dots)
pdf(\dots)
pictex(\dots)
#ifdef unix
png(\dots)
jpeg(\dots)
GNOME(\dots)
#endif
#ifdef windows
win.metafile(\dots)
win.print(\dots)
png(\dots)
jpeg(\dots)
bmp(\dots)
#endif
xfig(\dots)
bitmap(\dots)

dev.interactive()
}
\alias{Devices}
\alias{device}
\alias{dev.interactive}
\description{The following graphics devices are currently available:
  \itemize{
    \item \code{\link{postscript}} Writes PostScript graphics commands to
    a file
    \item \code{\link{pdf}} Write PDF graphics commands to a file
    \item \code{\link{pictex}} Writes LaTeX/PicTeX graphics commands to a
    file
#ifdef windows
    \item \code{\link{windows}} The graphics driver for Windows (on screen,
    to printer and to Windows metafile).
    \item \code{\link{png}} PNG bitmap device
    \item \code{\link{jpeg}} JPEG bitmap device
    \item \code{\link{bmp}} BMP bitmap device
#endif
    \item \code{\link{xfig}} Device for XFIG graphics file format
    \item \code{\link{bitmap}} bitmap pseudo-device via
    \code{GhostScript} (if available).
  }
#ifdef unix
  The following devices will be available if \R was compiled to use them
  and started with the appropriate \option{--gui} argument:
  \itemize{
    \item \code{\link{X11}} The graphics driver for the X11 Window
    system
    \item \code{\link{png}} PNG bitmap device
    \item \code{\link{jpeg}} JPEG bitmap device
    \code{\link{GNOME}} Graphics driver for the GNOME GUI.
%% <FIXME>  quartz() also with corresponding --gui aqua ?
#ifdef aqua
%%     ^^^^ not yet available
    \item \code{\link{quartz}} The graphics driver for the Mac OSX
    native aqua system.
#endif
%% </FIXME>
  }
  None of these are available under \code{R CMD \link[base:BATCH]{BATCH}}.
#endif
}
\value{
  \code{dev.interactive()} returns a logical, \code{TRUE} iff an
  interactive (screen) device is in use.
}
\details{
  If no device is open, using a high-level graphics function will cause
  a device to be opened.  Which device is given by
  \code{\link{options}("device")} which is initially set as the most
  appropriate for each platform: a screen device for most interactive use and
  \code{\link{postscript}} otherwise. The exception is  interactive
  use under Unix if no screen device is known to be available, when
  postscript() is used for most systems; pdf() for Mac OS X.
}
\seealso{
  The individual help files for further information on any of the
  devices listed here;

  \code{\link{dev.cur}}, \code{\link{dev.print}},
  \code{\link{graphics.off}}, \code{\link{image}},
  \code{\link{dev2bitmap}}.
#ifdef unix

  \code{\link{capabilities}} to see if \code{\link{X11}}, \code{\link{jpeg}}
  and \code{\link{png}} are available.
%% FIXME: aqua / quartz ?
#endif
}
\examples{\dontrun{
## open the default screen device on this platform if no device is
## open
if(dev.cur() == 1) get(getOption("device"))()
}}
\keyword{device}
\eof
%% NB: Microsoft Help Compiler often crashes on this file
%% Do not alter unless you have checked on Windows!
\name{Hershey}
\alias{Hershey}
\title{Hershey Vector Fonts in R}
\usage{
Hershey
}
\description{
  If the \code{vfont} argument to one of the text-drawing functions
  (\code{\link{text}}, \code{\link{mtext}}, \code{\link{title}},
  \code{\link{axis}}, and \code{\link{contour}}) is a character vector
  of length 2, Hershey vector fonts are used to render the text.

  These fonts have two advantages:\cr
  \enumerate{
    \item vector fonts describe each
    character in terms of a set of points;  \R renders the character by
    joining up the points with straight lines.  This intimate knowledge of
    the outline of each character means that \R can arbitrarily transform
    the characters, which can mean that the vector fonts look better
    for rotated and 3d text.
    \item this implementation was adapted from the GNU libplot library
    which provides support for non-ASCII and non-English fonts.  This means
    that it is possible, for example, to produce weird plotting symbols and
    Japanese characters.
  }

  Drawback:\cr
  You cannot use mathematical expressions (\code{\link{plotmath}}) with
  Hershey fonts.
}
\details{
  The Hershey characters are organised into a set of fonts, which are
  specified by a typeface (e.g., \code{serif} or \code{sans serif})
  and a fontindex or \dQuote{style} (e.g., \code{plain} or \code{italic}).
  The first element of \code{vfont} specifies the typeface and the second
  element specifies the fontindex.  The first table
  produced by \code{demo(Hershey)} shows the character \code{a} produced
  by each of the different fonts.

  The available \code{typeface} and \code{fontindex} values are
  available as list components of the variable \code{Hershey}.
  The allowed pairs for \code{(typeface, fontindex)} are:
%% This is checked (via max{#}) in FixupVFont() ../../../main/plot.c
%% The basic "table" really is in  ../../../modules/vfonts/g_fontdb.c

  \tabular{ll}{
    serif \tab plain \cr
    serif \tab italic \cr
    serif \tab bold \cr
    serif \tab bold italic \cr
    serif \tab cyrillic \cr
    serif \tab oblique cyrillic \cr
    serif \tab EUC \cr
    sans serif \tab plain \cr
    sans serif \tab italic \cr
    sans serif \tab bold \cr
    sans serif \tab bold italic \cr
    script \tab plain \cr
    script \tab italic \cr
    script \tab bold \cr
    gothic english \tab plain \cr
    gothic german \tab plain \cr
    gothic italian \tab plain \cr
    serif symbol \tab plain \cr
    serif symbol \tab italic \cr
    serif symbol \tab bold \cr
    serif symbol \tab bold italic \cr
    sans serif symbol \tab plain \cr
    sans serif symbol \tab italic \cr
  }
  and the indices of these are available as \code{Hershey$allowed}.

  \describe{
    \item{Escape sequences:}{The string to be drawn can include escape
      sequences, which all begin with a \code{\\}.   When \R encounters a
      \code{\\}, rather than drawing the \code{\\}, it treats the
      subsequent character(s) as a coded description of what to draw.

      One useful escape sequence (in the current context) is of the
      form: \code{\\123}.  The three digits following the \code{\\} specify an
      octal code for a character.  For example, the octal code for \code{p} is
      160 so the strings \code{"p"} and \code{"\\160"} are equivalent. This is
      useful for producing characters when there is not an appropriate key on
      your keyboard.

      The other useful escape sequences all begin with \code{\\\\}.  These are
      described below.
      Remember that backslashes have to be doubled in \R character
      strings, so they need to be entered with \emph{four} backslashes.
    }

    \item{Symbols:}{an entire string of Greek symbols can be produced by
      selecting the Serif Symbol or Sans Serif Symbol typeface.  To allow
      Greek symbols to be embedded in a string which uses a non-symbol
      typeface, there are a set of symbol escape sequences of the form
      \code{\\\\ab}. For example, the escape sequence \code{\\\\*a} produces a
      Greek alpha. The second table in \code{demo(Hershey)} shows all of the
      symbol escape sequences and the symbols that they produce.
    }

    \item{ISO Latin-1:}{further escape sequences of the form \code{\\\\ab} are
      provided for producing ISO Latin-1 characters (for example, if
      you only have a US keyboard).  Another option is to use the appropriate
      octal code.  The (non-ASCII) ISO Latin-1 characters are in the range
      241\dots377.  For example, \code{\\366} produces the character \code{o}
      with an umlaut.  The third table in \code{demo(Hershey)} shows all
      of the ISO Latin-1 escape sequences.
    }

    \item{Special Characters:}{a set of characters are provided which
      do not fall into any standard font.  These can only be accessed by
      escape sequence.  For example, \code{\\\\LI} produces the zodiac sign for
      Libra, and \code{\\\\JU} produces the astronomical sign for Jupiter.
      The fourth table in \code{demo(Hershey)} shows all of the
      special character escape sequences.
    }

    \item{Cyrillic Characters:}{cyrillic characters are implemented
      according to the K018-R encoding.  On a US keyboard, these can be
      produced using the Serif typeface and Cyrillic (or Oblique Cyrillic)
      fontindex and specifying an octal code in the range 300 to 337 for
      lower case characters or 340 to 377 for upper case characters.
      The fifth table in \code{demo(Hershey)} shows the octal codes for
      the available cyrillic characters.
    }

    \item{Japanese Characters:}{83 Hiragana, 86 Katakana, and 603 Kanji
      characters are implemented according to the EUC (Extended Unix Code)
      encoding. Each character is identified by a unique hexadecimal code.
      The Hiragana characters
      are in the range 0x2421 to 0x2473, Katakana are in the range 0x2521 to
      0x2576, and Kanji are (scattered about) in the range 0x3021 to 0x6d55.

      When using the Serif typeface and EUC
      fontindex, these characters can be produced by a \emph{pair} of octal
      codes.  Given the hexadecimal code (e.g., 0x2421), take the first two
      digits and add 0x80 and do the same to the second two digits (e.g.,
      0x21 and 0x24 become 0xa4 and 0xa1), then convert both to octal (e.g.,
      0xa4 and 0xa1 become 244 and 241).  For example, the first Hiragana
      character is produced by \code{\\244\\241}.

      It is also possible to use the hexadecimal code directly.  This works
      for all non-EUC fonts by specifying an escape sequence of the form
      \code{\\\\#J1234}.  For example, the first Hiragana character is produced
      by \code{\\\\#J2421}.

      The Kanji characters may be specified in a third way, using the
      so-called "Nelson Index", by specifying an escape sequence of the form
      \code{\\\\#N1234}.  For example, the Kanji for \dQuote{one} is
      produced by \code{\\\\#N0001}.
    
      \code{demo(Japanese)} shows the available Japanese characters.
    }
      
    \item{Raw Hershey Glyphs:}{all of the characters in the Hershey fonts
      are stored in a large array.  Some characters are not accessible in
      any of the Hershey fonts.  These characters can only be accessed via
      an escape sequence of the form \code{\\\\#H1234}.  For example, the
      fleur-de-lys is produced by \code{\\\\#H0746}.  The sixth and seventh
      tables of \code{demo(Hershey)} shows all of the available raw
      glyphs.
    }
  }
}
\references{
  \url{http://www.gnu.org/software/plotutils/plotutils.html}
}
\seealso{
  \code{demo(Hershey)}, \code{\link{text}}, \code{\link{contour}}.

  \code{\link{Japanese}} for the Japanese characters in the Hershey fonts.
}
\examples{
Hershey

## for tables of examples, see demo(Hershey)
}
\keyword{aplot}
\eof
\name{Japanese}
\alias{Japanese}
\title{Japanese characters in R}
\description{
  The implementation of Hershey vector fonts provides a large number of
  Japanese characters (Hiragana, Katakana, and Kanji).
}
\details{
  Without keyboard support for typing Japanese characters, the only way
  to produce these characters is to use special escape sequences: see
  \code{\link{Hershey}}.

  For example, the Hiragana character for the sound "ka" is produced
  by \code{\\\\#J242b} and the Katakana character for this sound is
  produced by \code{\\\\#J252b}.  The Kanji ideograph for "one" is
  produced by \code{\\\\#J306c} or \code{\\\\#N0001}.

  The output from \code{demo(Japanese)} shows tables of the escape
  sequences for the available Japanese characters.
}
\seealso{
  \code{demo(Japanese)},
  \code{\link{Hershey}},
  \code{\link{text}},
  \code{\link{contour}}
}
\references{
  \url{http://www.gnu.org/software/plotutils/plotutils.html}
}
\examples{
plot(1:9, type="n", axes=FALSE, frame=TRUE, ylab="",
     main= "example(Japanese)", xlab= "using Hershey fonts")
par(cex=3)
Vf <- c("serif", "plain")
% doubled "\" -> can't execute here!
text(4, 2, "\\\\#J2438\\\\#J2421\\\\#J2451\\\\#J2473", vfont = Vf)
text(4, 4, "\\\\#J2538\\\\#J2521\\\\#J2551\\\\#J2573", vfont = Vf)
text(4, 6, "\\\\#J467c\\\\#J4b5c", vfont = Vf)
text(4, 8, "Japan", vfont = Vf)
par(cex=1)
text(8, 2, "Hiragana")
text(8, 4, "Katakana")
text(8, 6, "Kanji")
text(8, 8, "English")
}
\keyword{aplot}
\eof
\name{abline}
\alias{abline}
\title{Add a Straight Line to a Plot}
\description{
  This function adds one or more straight lines through the current plot.
}
\synopsis{
abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, untf = FALSE, col = par("col"),
       lty = par("lty"), lwd = NULL, ...)
}
\usage{
abline(a, b, untf = FALSE, \dots)
abline(h=, untf = FALSE, \dots)
abline(v=, untf = FALSE, \dots)
abline(coef=, untf = FALSE, \dots)
abline(reg=, untf = FALSE, \dots)
}
\arguments{
  \item{a,b}{the intercept and slope.}
  \item{untf}{logical asking to \emph{untransform}.  See Details.}
  \item{h}{the y-value for a horizontal line.}
  \item{v}{the x-value for a vertical line.}
  \item{coef}{a vector of length two giving the intercept and slope.}
  \item{reg}{an object with a \code{coef} component. See Details.}
  \item{\dots}{graphical parameters.}
}
\details{
  The first form specifies the line in intercept/slope form
  (alternatively \code{a} can be specified on its own and is taken to
  contain the slope and intercept in vector form).

  The \code{h=} and \code{v=} forms draw horizontal and vertical lines
  at the specified coordinates.

  The \code{coef} form specifies the line by a vector containing the
  slope and intercept.

  \code{reg} is a regression object which contains \code{reg$coef}.  If
  it is of length 1 then the value is taken to be the slope of a line
  through the origin, otherwise, the first 2 values are taken to be the
  intercept and slope.

  If \code{untf} is true, and one or both axes are log-transformed, then
  a curve is drawn corresponding to a line in original coordinates,
  otherwise a line is drawn in the transformed coordinate system. The
  \code{h} and \code{v} parameters always refer to original coordinates.

  The graphical parameters \code{col} and \code{lty} can be specified as
  arguments to \code{abline}; see \code{par} for details.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{lines}} and \code{\link{segments}} for connected and
  arbitrary lines given by their \emph{endpoints}.
  \code{\link{par}}.
}
\examples{
data(cars)
z <- lm(dist ~ speed, data = cars)
plot(cars)
abline(z)
}
\keyword{aplot}
\eof
\name{arrows}
\title{Add Arrows to a Plot}
\usage{
arrows(x0, y0, x1, y1, length = 0.25, angle = 30, code = 2,
       col = par("fg"), lty = NULL, lwd = par("lwd"), xpd = NULL)
}
\alias{arrows}
\arguments{
  \item{x0, y0}{coordinates of points \bold{from} which to draw.}
  \item{x1, y1}{coordinates of points \bold{to} which to draw.}
  \item{length}{length of the edges of the arrow head (in inches).}
  \item{angle}{angle from the shaft of the arrow to the edge of the
    arrow head.}
  \item{code}{integer code, determining \emph{kind} of arrows to be
    drawn.}
  \item{col, lty, lwd, xpd}{usual graphical parameters as in
    \code{\link{par}}.}
}
\description{
  Draw arrows between pairs of points.
}
\details{
  For each \code{i}, an arrow is drawn between the point \code{(x0[i],
    y0[i])} and the point \code{(x1[i],y1[i])}.

  If \code{code=2} an arrowhead is drawn at \code{(x0[i],y0[i])} and if
  \code{code=1} an arrowhead is drawn at \code{(x1[i],y1[i])}.  If
  \code{code=3} a head is drawn at both ends of the arrow.  Unless
  \code{length = 0}, when no head is drawn.

  The graphical parameters \code{col} and \code{lty} can be used
  to specify a color and line texture for the line segments which
  make up the arrows (\code{col} may be a vector).

  The direction of a zero-length arrow is indeterminate, and hence so is
  the direction of the arrowheads.  To allow for rounding error,
  arrowheads are omitted (with a warning) on any arrow of length less
  than 1/1000 inch.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{segments}} to draw segments.
}
\examples{
x <- runif(12); y <- rnorm(12)
i <- order(x,y); x <- x[i]; y <- y[i]
plot(x,y, main="arrows(.) and segments(.)")
## draw arrows from point to point :
s <- seq(length(x)-1)# one shorter than data
arrows(x[s], y[s], x[s+1], y[s+1], col= 1:3)
s <- s[-length(s)]
segments(x[s], y[s], x[s+2], y[s+2], col= 'pink')
}
\keyword{aplot}
\eof
\name{assocplot}
\alias{assocplot}
\title{Association Plots}
\description{
  Produce a Cohen-Friendly association plot indicating deviations from
  independence of rows and columns in a 2-dimensional contingency
  table.
}
\usage{
assocplot(x, col = c("black", "red"), space = 0.3,
          main = NULL, xlab = NULL, ylab = NULL)
}
\arguments{
  \item{x}{a two-dimensional contingency table in matrix form.}
  \item{col}{a character vector of length two giving the colors used for
    drawing positive and negative Pearson residuals, respectively.}
  \item{space}{the amount of space (as a fraction of the average
    rectangle width and height) left between each rectangle.}
  \item{main}{overall title for the plot.}
  \item{xlab}{a label for the x axis.  Defaults to the name of the row
    variable in \code{x} if non-\code{NULL}.}
  \item{ylab}{a label for the y axis.  Defaults to the column names of
    the column variable in \code{x} if non-\code{NULL}.}
}
\details{
  For a two-way contingency table, the signed contribution to Pearson's
  \eqn{\chi^2}{chi^2} for cell \eqn{i, j} is \eqn{d_{ij} = (f_{ij} -
    e_{ij}) / \sqrt{e_{ij}}}{d_{ij} = (f_{ij} - e_{ij}) / sqrt(e_{ij})},
  where \eqn{f_{ij}} and \eqn{e_{ij}} are the observed and expected
  counts corresponding to the cell.  In the Cohen-Friendly association
  plot, each cell is represented by a rectangle that has (signed) height
  proportional to \eqn{d_{ij}} and width proportional to
  \eqn{\sqrt{e_{ij}}}{sqrt(e_{ij})}, so that the area of the box is
  proportional to the difference in observed and expected frequencies.
  The rectangles in each row are positioned relative to a baseline
  indicating independence (\eqn{d_{ij} = 0}).  If the observed frequency
  of a cell is greater than the expected one, the box rises above the
  baseline and is shaded in the color specified by the first element of
  \code{col}, which defaults to black; otherwise, the box falls below
  the baseline and is shaded in the color specified by the second
  element of \code{col}, which defaults to red.
}
\seealso{
  \code{\link{mosaicplot}}; \code{\link[stats]{chisq.test}}.
}
\references{
  Cohen, A. (1980),
  On the graphical display of the significant components in a two-way
  contingency table.
  \emph{Communications in Statistics---Theory and Methods}, \bold{A9},
  1025--1041.

  Friendly, M. (1992),
  Graphical methods for categorical data.
  \emph{SAS User Group International Conference Proceedings}, \bold{17},
  190--200.
  \url{http://www.math.yorku.ca/SCS/sugi/sugi17-paper.html}
}
\examples{
data(HairEyeColor)
## Aggregate over sex:
x <- margin.table(HairEyeColor, c(1, 2))
x
assocplot(x, main = "Relation between hair and eye color")
}
\keyword{hplot}
\eof
\name{axTicks}
\alias{axTicks}
\title{Compute Axis Tickmark Locations}
\description{
  Compute pretty tickmark locations, the same way as \R does internally.
  This is only non-trivial when \bold{log} coordinates are active.
  By default, gives the \code{at} values which
  \code{\link{axis}(side)} would use.
}
\usage{
axTicks(side, axp = NULL, usr = NULL, log = NULL)
}
\arguments{
  \item{side}{integer in 1:4, as for \code{\link{axis}}.}
  \item{axp}{numeric vector of length three, defaulting to
    \code{\link{par}("Zaxp")} where \dQuote{Z} is \dQuote{x} or
    \dQuote{y} depending on the \code{side} argument.}
  \item{usr}{numeric vector of length four, defaulting to
    \code{\link{par}("usr")} giving horizontal (\sQuote{x}) and vertical
    (\sQuote{y}) user coordinate limits.}
  \item{log}{logical indicating if log coordinates are active; defaults
    to \code{\link{par}("Zlog")} where \sQuote{Z} is as for the
    \code{axp} argument above.}
}
\details{
  The \code{axp}, \code{usr}, and \code{log} arguments must be consistent
  as their default values (the \code{par(..)} results) are.  If you
  specify all three (as non-NULL), the graphics environment is not used
  at all.  Note that the meaning of \code{axp} alters very much when \code{log}
  is \code{TRUE}, see the documentation on \code{\link{par}(xaxp=.)}.

  \code{axTicks()} can be regarded as an \R implementation  of the
  C function \code{CreateAtVector()} in \file{..../src/main/plot.c}
  which is called by \code{\link{axis}(side,*)} when no argument
  \code{at} is specified.
}
\value{
  numeric vector of coordinate values at which axis tickmarks can be
  drawn.  By default, when only the first argument is specified,
  these values should be identical to those that
  \code{\link{axis}(side)} would use or has used.
}
\seealso{\code{\link{axis}}, \code{\link{par}}.  \code{\link{pretty}}
  uses the same algorithm (but independently of the graphics
  environment) and has more options.  However it is not available for
  \code{log = TRUE.}
}
\examples{
 plot(1:7, 10*21:27)
 axTicks(1)
 axTicks(2)
 stopifnot(identical(axTicks(1), axTicks(3)),
           identical(axTicks(2), axTicks(4)))

## Show how axTicks() and axis() correspond :
op <- par(mfrow = c(3,1))
for(x in 9999*c(1,2,8)) {
    plot(x,9, log = "x")
    cat(formatC(par("xaxp"),wid=5),";",T <- axTicks(1),"\n")
    rug(T, col="red")
}
par(op)
}
\keyword{dplot}

\eof
\name{axis.POSIXct}
\alias{axis.POSIXct}
\alias{plot.POSIXct}
\alias{plot.POSIXlt}
\alias{axis.Date}
\alias{plot.Date}
\title{Date and Date-time Plotting Functions}
\description{
  Functions to plot objects of classes \code{"POSIXlt"},
  \code{"POSIXct"} and \code{"Date"}  representing calendar dates and times. 
}
\usage{
axis.POSIXct(side, x, at, format, \dots)

axis.Date(side, x, at, format, \dots)

\method{plot}{POSIXct}(x, y, xlab = "", \dots)

\method{plot}{POSIXlt}(x, y, xlab = "", \dots)

\method{plot}{Date}(x, y, xlab = "", \dots)
}
\synopsis{
plot.POSIXct(x, y, xlab = "", axes = TRUE, frame.plot = axes, xaxt = par("xaxt"), ...)
plot.POSIXlt(x, y, xlab = "", axes = TRUE, frame.plot = axes, xaxt = par("xaxt"), ...)
plot.Date(x, y, xlab = "", axes = TRUE, frame.plot = axes, xaxt = par("xaxt"), ...)
axis.POSIXct(side, x, at, format, ...)
axis.Date(side, x, at, format, ...)
}
\arguments{
  \item{x, at}{A date-time object.}
  \item{y}{numeric values to be plotted against \code{x}.}
  \item{xlab}{a character string giving the label for the x axis.}
  \item{side}{See \code{\link{axis}}.}
  \item{format}{See \code{\link{strptime}}.}
  \item{\dots}{Further arguments to be passed from or to other methods,
    typically graphical parameters or arguments of
    \code{\link{plot.default}}.}
}
\details{
  The functions plot against an x-axis of date-times.
  \code{axis.POSIXct} and \code{axis.Date} work quite hard to choose
  suitable time units (years, months, days, hours, minutes or seconds)
  and a sensible output format, but this can be overridden by supplying
  a \code{format} specification.

  If \code{at} is supplied it specifies the locations of the ticks
  and labels whereas if \code{x} is specified a suitable grid of labels
  is chosen. 
}
\seealso{
  \link{DateTimeClasses}, \link{Dates} for details of the classes.
}
\examples{
res <- try(data(beav1, package = "MASS"))
if(!inherits(res, "try-error")) {
attach(beav1)
time <- strptime(paste(1990, day, time \%/\% 100, time \%\% 100),
                 "\%Y \%j \%H \%M")
plot(time, temp, type="l") # axis at 4-hour intervals.
# now label every hour on the time axis
plot(time, temp, type="l", xaxt="n")
r <- as.POSIXct(round(range(time), "hours"))
axis.POSIXct(1, at=seq(r[1], r[2], by="hour"), format="\%H")
rm(time)
detach(beav1)
}

plot(.leap.seconds, 1:22, type="n", yaxt="n",
     xlab="leap seconds", ylab="", bty="n")
rug(.leap.seconds)
## or as dates
lps <- as.Date(.leap.seconds)
plot(lps, 1:22, type="n", yaxt="n", xlab="leap seconds", ylab="", bty="n")
rug(lps)

## 100 random dates in a 10-week period
random.dates <- as.Date("2001/1/1") + 70*sort(runif(100))
plot(random.dates, 1:100)
# or for a better axis labelling
plot(random.dates, 1:100, xaxt="n")
axis.Date(1, at=seq(as.Date("2001/1/1"), max(random.dates)+6, "weeks"))
}
\keyword{utilities}
\keyword{chron}
\eof
\name{axis}
\alias{axis}
\title{Add an Axis to a Plot}
\description{Adds an axis to the current plot, allowing the
  specification of the side, position, labels, and other options.
}
\usage{
axis(side, at = NULL, labels = TRUE, tick = TRUE, line = NA,
     pos = NA, outer = FALSE, font = NA, vfont = NULL,
     lty = "solid", lwd = 1, col = NULL, \dots)
}
\arguments{
  \item{side}{an integer specifying which side of the plot the axis is
    to be drawn on.  The axis is placed as follows: 1=below,
  2=left, 3=above and 4=right.}
  \item{at}{the points at which tick-marks are to be drawn.  Non-finite
    (infinite, \code{NaN} or \code{NA}) values are omitted.  By default,
    when \code{NULL}, tickmark locations are computed, see Details below.}
  \item{labels}{this can either be a logical value specifying whether
    (numerical) annotations are to be made at the tickmarks, or a vector
    of character strings to be placed at the tickpoints.}
  \item{tick}{a logical value specifying whether tickmarks should be
    drawn}.
  \item{line}{the number of lines into the margin which the axis will
    be drawn.  This overrides the value of the graphical parameter
    \code{mgp[3]}.  The relative placing of tickmarks and tick labels
    is unchanged.}
  \item{pos}{the coordinate at which the axis line is to be drawn:
    this overrides the values of both \code{line} and \code{mgp[3]}.}
  \item{outer}{a logical value indicating whether the axis should be
    drawn in the outer plot margin, rather than the standard plot
    margin.}
  \item{font}{font for text.}
  \item{vfont}{vector font for text.}
  \item{lty, lwd}{line type, width for the axis line and the tick marks.}
  \item{col}{color for the axis line and the tick marks.  The default
    \code{NULL} means to use \code{par("fg")}.}
  \item{\dots}{other graphical parameters may also be passed as arguments to
    this function, particularly, \code{cex.axis}, \code{col.axis} and
    \code{font.axis} for axis annotation, \code{las} for
    vertical/horizontal label orientation, or \code{fg} instead of
    \code{col}, see \code{\link{par}} on these.}
}
\value{
  This function is invoked for its side effect, which is to add an axis
  to an already existing plot.
}
\details{
  The axis line is drawn from the lowest to the highest value of
  \code{at}, but will be clipped at the plot region. Only ticks which
  are drawn from points within the plot region (up to a tolerance for
  rounding error) are plotted, but the ticks and their labels may well
  extend outside the plot region.

  When \code{at = NULL}, pretty tick mark locations are computed internally
  (the same way \code{\link{axTicks}(side)} would) from
  \code{\link{par}("usr", "lab")} and \code{\link{par}("xlog")} (or
  \code{"ylog"}).

  Several of the graphics parameters affect the way axes are drawn. The
  vertical (for sides 1 and 3) positions of the axis and the tick labels
  are controlled by \code{mgp}, the size of the ticks is controlled by
  \code{tck} and \code{tcl} and the appearance of the tick labels by
  \code{cex.axis}, \code{col.axis} and \code{font.axis} with
  orientation controlled by \code{las} (but not \code{srt}, unlike S
  which uses \code{srt} if \code{at} is supplied and \code{las} if it is
  not).
}
\seealso{
  \code{\link{axTicks}} returns the axis tick locations
  corresponding to \code{at=NULL}; \code{\link{pretty}} is more flexible
  for computing pretty tick coordinates and does \emph{not} depend on
  (nor adapt to) the coordinate system in use.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
plot(1:4, rnorm(4), axes=FALSE)
axis(1, 1:4, LETTERS[1:4])
axis(2)
box() #- to make it look "as usual"

plot(1:7, rnorm(7), main = "axis() examples",
     type = "s", xaxt = "n", frame = FALSE, col = "red")
axis(1, 1:7, LETTERS[1:7], col.axis = "blue")
# unusual options:
axis(4, col = "violet", col.axis="dark violet", lwd = 2)
axis(3, col = "gold", lty = 2, lwd = 0.5)
}
\keyword{aplot}
\eof
\name{barplot}
\alias{barplot}
\alias{barplot.default}
\title{Bar Plots}
\description{
  Creates a bar plot with vertical or horizontal bars.
}
\usage{
\method{barplot}{default}(height, width = 1, space = NULL,
        names.arg = NULL, legend.text = NULL, beside = FALSE,
        horiz = FALSE, density = NULL, angle = 45,
        col = NULL, border = par("fg"),
        main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
        xlim = NULL, ylim = NULL, xpd = TRUE,
        axes = TRUE, axisnames = TRUE,
        cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
        inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0, \dots)
}
\arguments{
  \item{height}{either a vector or matrix of values describing the
    bars which make up the plot.  If \code{height} is a vector, the
    plot consists of a sequence of rectangular bars with heights
    given by the values in the vector.  If \code{height} is a matrix
    and \code{beside} is \code{FALSE} then each bar of the plot
    corresponds to a column of \code{height}, with the values in the
    column giving the heights of stacked \dQuote{sub-bars} making up the
    bar.  If \code{height} is a matrix and \code{beside} is
    \code{TRUE}, then the values in each column are juxtaposed
    rather than stacked.}
  \item{width}{optional vector of bar widths. Re-cycled to length the
    number of bars drawn.  Specifying a single value will no visible
    effect unless \code{xlim} is specified.}
  \item{space}{the amount of space (as a fraction of the average bar
    width) left before each bar.  May be given as a single number or
    one number per bar.  If \code{height} is a matrix and
    \code{beside} is \code{TRUE}, \code{space} may be specified by
    two numbers, where the first is the space between bars in the
    same group, and the second the space between the groups.  If not
    given explicitly, it defaults to \code{c(0,1)} if \code{height}
    is a matrix and \code{beside} is \code{TRUE}, and to 0.2
    otherwise.}
  \item{names.arg}{a vector of names to be plotted below each bar or
    group of bars.  If this argument is omitted, then the names are
    taken from the \code{names} attribute of \code{height} if this
    is a vector, or the column names if it is a matrix.}
  \item{legend.text}{a vector of text used to construct a legend for
    the plot, or a logical indicating whether a legend should be
    included.  This is only useful when \code{height} is a matrix.
    In that case given legend labels should correspond to the rows of
    \code{height}; if \code{legend.text} is true, the row names of
    \code{height} will be used as labels if they are non-null.}
  \item{beside}{a logical value.  If \code{FALSE}, the columns of
    \code{height} are portrayed as stacked bars, and if \code{TRUE}
    the columns are portrayed as juxtaposed bars.}
  \item{horiz}{a logical value.  If \code{FALSE}, the bars are drawn
    vertically with the first bar to the left.  If \code{TRUE}, the
    bars are drawn horizontally with the first at the bottom.}
  \item{density}{a vector giving the density of shading lines, in
    lines per inch, for the bars or bar components.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise), for the bars or bar components.}
  \item{col}{a vector of colors for the bars or bar components.
    By default, grey is used if \code{height} is a vector, and
    \code{heat.colors(nrow(height))} if \code{height} is a matrix.}
  \item{border}{the color to be used for the border of the bars.}
  \item{main,sub}{overall and sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}
  \item{xlim}{limits for the x axis.}
  \item{ylim}{limits for the y axis.}
  \item{xpd}{logical. Should bars be allowed to go outside region?}
  \item{axes}{logical.  If \code{TRUE}, a vertical (or horizontal, if
    \code{horiz} is true) axis is drawn.}
  \item{axisnames}{logical.  If \code{TRUE}, and if there are
    \code{names.arg} (see above), the
    other axis is drawn (with \code{lty=0}) and labeled.}
  \item{cex.axis}{expansion factor for numeric axis labels.}
  \item{cex.names}{expansion factor for axis names (bar labels).}
  \item{inside}{logical.  If \code{TRUE}, the lines which divide
    adjacent (non-stacked!) bars will be drawn.  Only applies when
    \code{space = 0} (which it partly is when \code{beside = TRUE}).}
%MM: we still have "NotYetUsed" -- the above describe's S-plus 6.1 (not
% precisely documented!) behavior!
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted.}
  \item{axis.lty}{the graphics parameter \code{lty} applied to the axis
    and tick marks of the categorical (default horizontal) axis.  Note
    that by default the axis is suppressed.}
  \item{offset}{a vector indicating how much the bars should be shifted
    relative to the x axis.}
  \item{\dots}{further graphical parameters (\code{\link{par}}) are
    passed to \code{\link{plot.window}()}, \code{\link{title}()} and
    \code{\link{axis}}.}
}
\details{
  This is a generic function, it currently only has a default method.
  A formula interface may be added eventually.
}
\value{
  A numeric vector (or matrix, when \code{beside = TRUE}), say
  \code{mp}, giving the coordinates of \emph{all} the bar midpoints
  drawn, useful for adding to the graph.

  If \code{beside} is true, use \code{colMeans(mp)} for the
  midpoints of each \emph{group} of bars, see example.
}
\note{
  Prior to \R 1.6.0, \code{barplot} behaved as if \code{axis.lty = 1},
  unintentionally.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}(\dots, type="h")}, \code{\link{dotchart}},
  \code{\link{hist}}.
}
\examples{
tN <- table(Ni <- rpois(100, lambda=5))
r <- barplot(tN, col='gray')
#- type = "h" plotting *is* 'bar'plot
lines(r, tN, type='h', col='red', lwd=2)

barplot(tN, space = 1.5, axisnames=FALSE,
        sub = "barplot(..., space= 1.5, axisnames = FALSE)")

data(VADeaths, package = "base")
barplot(VADeaths, plot = FALSE)
barplot(VADeaths, plot = FALSE, beside = TRUE)

mp <- barplot(VADeaths) # default
tot <- colMeans(VADeaths)
text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")
barplot(VADeaths, beside = TRUE,
        col = c("lightblue", "mistyrose", "lightcyan",
                "lavender", "cornsilk"),
        legend = rownames(VADeaths), ylim = c(0, 100))
title(main = "Death Rates in Virginia", font.main = 4)

hh <- t(VADeaths)[, 5:1]
mybarcol <- "gray20"
mp <- barplot(hh, beside = TRUE,
        col = c("lightblue", "mistyrose",
                "lightcyan", "lavender"),
        legend = colnames(VADeaths), ylim= c(0,100),
        main = "Death Rates in Virginia", font.main = 4,
        sub = "Faked upper 2*sigma error bars", col.sub = mybarcol,
        cex.names = 1.5)
segments(mp, hh, mp, hh + 2*sqrt(1000*hh/100), col = mybarcol, lwd = 1.5)
stopifnot(dim(mp) == dim(hh))# corresponding matrices
mtext(side = 1, at = colMeans(mp), line = -2,
      text = paste("Mean", formatC(colMeans(hh))), col = "red")

# Bar shading example
barplot(VADeaths, angle = 15+10*1:5, density = 20, col = "black",
        legend = rownames(VADeaths))
title(main = list("Death Rates in Virginia", font = 4))

# border :
barplot(VADeaths, border = "dark blue") % lwd = 2 << not passed
%notyet barplot(VADeaths, inside = FALSE, main = "barplot(*, inside=FALSE)")
}
\keyword{hplot}
\eof
\name{box}
\title{Draw a Box around a Plot}
\usage{
box(which="plot", lty="solid", \dots)
}
\alias{box}
\arguments{
\item{which}{character, one of \code{"plot"}, \code{"figure"},
  \code{"inner"} and \code{"outer"}.}
\item{lty}{line type of the box.}
\item{\dots}{further graphical parameters, such as
  \code{bty}, \code{col}, or \code{lwd}, see \code{\link{par}}.}
}
\description{
This function draws a box around the current plot in the given color
and linetype.  The \code{bty} parameter determines
the type of box drawn.  See \code{\link{par}} for details.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
\code{\link{rect}} for drawing of arbitrary rectangles.
}
\examples{
plot(1:7,abs(rnorm(7)), type='h', axes = FALSE)
axis(1, labels = letters[1:7])
box(lty='1373', col = 'red')
}
\keyword{aplot}
\eof
\name{boxplot}
\alias{boxplot}
\alias{boxplot.default}
\alias{boxplot.formula}
\title{Box Plots}
\description{
  Produce box-and-whisker plot(s) of the given (grouped) values.
}
\usage{
boxplot(x, \dots)

\method{boxplot}{formula}(formula, data = NULL, \dots, subset)

\method{boxplot}{default}(x, \dots, range = 1.5, width = NULL, varwidth = FALSE,
        notch = FALSE, outline = TRUE, names, boxwex = 0.8, plot = TRUE,
        border = par("fg"), col = NULL, log = "", pars = NULL,
        horizontal = FALSE, add = FALSE, at = NULL)
}
\arguments{
  \item{formula}{a formula, such as \code{y ~ grp}, where \code{y} is a
    numeric vector of data values to be split into groups according to
    the grouping variable \code{grp} (usually a factor).}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
  \item{x}{for specifying data from which the boxplots are to be
    produced. Either a numeric vector, or a single list containing such
    vectors. Additional unnamed arguments specify further data
    as separate vectors (each corresponding to a component boxplot).
    \code{\link{NA}}s are allowed in the data.}
  \item{\dots}{For the \code{formula} method, arguments to the
    default method and graphical parameters.

    For the default method, unnamed arguments are additional data
    vectors (unless \code{x} is a list when they are ignored),
    and named arguments are graphical parameters in addition to the ones
    given by argument \code{pars}.
  }
  \item{range}{this determines how far the plot whiskers extend out
    from the box.  If \code{range} is positive, the whiskers extend
    to the most extreme data point which is no more than
    \code{range} times the interquartile range from the box. A value
    of zero causes the whiskers to extend to the data extremes.}
  \item{width}{a vector giving the relative widths of the boxes making
    up the plot.}
  \item{varwidth}{if \code{varwidth} is \code{TRUE}, the boxes are
    drawn with widths proportional to the square-roots of the number
    of observations in the groups.}
  \item{notch}{if \code{notch} is \code{TRUE}, a notch is drawn in
    each side of the boxes.  If the notches of two plots do not
    overlap this is \sQuote{strong evidence} that the two medians differ
    (Chambers \emph{et al.}, 1983, p. 62).  See \code{\link{boxplot.stats}}
    for the calculations used.}
  \item{outline}{if \code{outline} is not true, the outliers are
    not drawn (as points whereas S+ uses lines).}% the argument name is most ugly but S+ compatible
  \item{names}{group labels which will be printed under each boxplot.}
  \item{boxwex}{a scale factor to be applied to all boxes.  When there
    are only a few groups, the appearance of the plot can be improved
    by making the boxes narrower.}
  \item{plot}{if \code{TRUE} (the default) then a boxplot is
    produced.  If not, the summaries which the boxplots are based on
    are returned.}
  \item{border}{an optional vector of colors for the outlines of the
    boxplots.  The values in \code{border} are recycled if the
    length of \code{border} is less than the number of plots.}
  \item{col}{if \code{col} is non-null it is assumed to contain colors
    to be used to colour the bodies of the box plots.}
  \item{log}{character indicating if x or y or both coordinates should
    be plotted in log scale.}
  \item{pars}{a list of graphical parameters; these are passed to
    \code{\link{bxp}} (if \code{plot} is true).}
  \item{horizontal}{logical indicating if the boxplots should be
    horizontal; default \code{FALSE} means vertical boxes.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots should
    be drawn, particularly when \code{add = TRUE};
    defaults to \code{1:n} where \code{n} is the number of boxes.}
}
\details{
  The generic function \code{boxplot} currently has a default method
  (\code{boxplot.default}) and a formula interface
  (\code{\link{boxplot.formula}}).
}
\value{
  List with the following components:
  \item{stats}{a matrix, each column contains the extreme of the lower
    whisker, the lower hinge, the median, the upper hinge and the
    extreme of the upper whisker for one group/plot.}
  \item{n}{a vector with the number of observations in each group.}
  \item{conf}{a matrix where each column contains the lower and upper
    extremes of the notch.}
  \item{out}{the values of any data points which lie beyond the
    extremes of the whiskers.}
  \item{group}{a vector of the same length as \code{out} whose elements
    indicate which group the outlier belongs to}
  \item{names}{a vector of names for the groups}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis.}  Wadsworth \& Brooks/Cole.

  See also \code{\link{boxplot.stats}}.
}
\seealso{
  \code{\link{boxplot.stats}} which does the computation,
  \code{\link{bxp}} for the plotting;
  and \code{\link{stripchart}} for an alternative (with small data
  sets).
}
\examples{
## boxplot on a formula:
data(InsectSprays)
boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
# *add* notches (somewhat funny here):
boxplot(count ~ spray, data = InsectSprays,
        notch = TRUE, add = TRUE, col = "blue")

data(OrchardSprays)
boxplot(decrease ~ treatment, data = OrchardSprays,
        log = "y", col="bisque")

rb <- boxplot(decrease ~ treatment, data = OrchardSprays, col="bisque")
title("Comparing boxplot()s and non-robust mean +/- SD")

mn.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, mean)
sd.t <- tapply(OrchardSprays$decrease, OrchardSprays$treatment, sd)
xi <- 0.3 + seq(rb$n)
points(xi, mn.t, col = "orange", pch = 18)
arrows(xi, mn.t - sd.t, xi, mn.t + sd.t,
       code = 3, col = "pink", angle = 75, length = .1)

## boxplot on a matrix:
mat <- cbind(Uni05 = (1:100)/21, Norm = rnorm(100),
             T5 = rt(100, df = 5), Gam2 = rgamma(100, shape = 2))
boxplot(data.frame(mat), main = "boxplot(data.frame(mat), main = ...)")
par(las=1)# all axis labels horizontal
boxplot(data.frame(mat), main = "boxplot(*, horizontal = TRUE)",
        horizontal = TRUE)

## Using 'at = ' and adding boxplots -- example idea by Roger Bivand :

data(ToothGrowth)
boxplot(len ~ dose, data = ToothGrowth,
        boxwex = 0.25, at = 1:3 - 0.2,
        subset= supp == "VC", col="yellow",
        main="Guinea Pigs' Tooth Growth",
        xlab="Vitamin C dose mg",
        ylab="tooth length", ylim=c(0,35))
boxplot(len ~ dose, data = ToothGrowth, add = TRUE,
        boxwex = 0.25, at = 1:3 + 0.2,
        subset= supp == "OJ", col="orange")
legend(2, 9, c("Ascorbic acid", "Orange juice"),
       fill = c("yellow", "orange"))
}
\keyword{hplot}
\eof
\name{boxplot.stats}
\title{Box Plot Statistics}
\usage{
boxplot.stats(x, coef = 1.5, do.conf=TRUE, do.out=TRUE)
}
\alias{boxplot.stats}
\arguments{
  \item{x}{a numeric vector for which the boxplot will
    be constructed (\code{\link{NA}}s and \code{\link{NaN}}s are allowed
    and omitted).}
  \item{coef}{this determines how far the plot \dQuote{whiskers} extend out
    from the box.  If \code{coef} is positive, the whiskers extend to the
    most extreme data point which is no more than \code{coef} times
    the length of the box away from the box. A value of zero causes
    the whiskers
    to extend to the data extremes (and no outliers be returned).}
  \item{do.conf,do.out}{logicals; if \code{FALSE}, the \code{conf} or
    \code{out} component respectively will be empty in the result.}
}
\description{
  This function is typically called by \code{\link{boxplot}} to
  gather the statistics necessary for producing box plots,
  but may be invoked separately.
}
\value{
  List with named components as follows:
  \item{stats}{a vector of length 5, containing the extreme of the
    lower whisker, the lower \dQuote{hinge}, the median, the upper
    \dQuote{hinge} and the extreme of the upper whisker.}
  \item{n}{the number of non-\code{NA} observations in the sample.}
  \item{conf}{the lower and upper extremes of the \dQuote{notch}
    (\code{if(do.conf)}). See the details.}
  \item{out}{the values of any data points which lie beyond the
    extremes of the whiskers (\code{if(do.out)}).}

  Note that \code{$stats} and \code{$conf} are sorted in \emph{in}creasing
  order, unlike S, and that \code{$n} and \code{$out} include any
  \code{+- Inf} values.
}
\details{
  The two \dQuote{hinges} are versions of the first and third quartile,
  i.e., close to \code{\link[stats]{quantile}(x, c(1,3)/4)}.  The hinges equal
  the quartiles for odd \eqn{n} (where \code{n <- length(x)}) and
  differ for even \eqn{n}. Where the quartiles only equal observations
  for \code{n \%\% 4 == 1} (\eqn{n\equiv 1 \bmod 4}{n = 1 mod 4}),
  the hinges do so \emph{additionally} for \code{n \%\% 4 == 2}
  (\eqn{n\equiv 2 \bmod 4}{n = 2 mod 4}), and are in the middle of
  two observations otherwise.

  The notches (if requested) extend to \code{+/-1.58 IQR/sqrt(n)}.
  This seems to be based on same calculations as the formula with 1.57 in
  Chambers \emph{et al.} (1983, p. 62), given in McGill \emph{et al.}
  (1978, p. 16).  They are based on asymptotic normality of the median
  and roughly equal sample sizes for the two medians being compared, and
  are said to be rather insensitive to the underlying distributions of
  the samples.  The idea appears to be to give roughly a 95\% confidence
  interval for the difference in two medians.
}
\references{
  Tukey, J. W. (1977) \emph{Exploratory Data Analysis.} Section 2C.

  McGill, R., Tukey, J. W. and Larsen, W. A. (1978) Variations of box
  plots. \emph{The American Statistician} \bold{32}, 12--16.

  Velleman, P. F. and Hoaglin, D. C. (1981) \emph{Applications, Basics
    and Computing of Exploratory Data Analysis.}  Duxbury Press.

  Emerson, J. D and Strenio, J. (1983). Boxplots and batch comparison.
  Chapter 3 of \emph{Understanding Robust and Exploratory Data
    Analysis}, eds. D. C. Hoaglin, F. Mosteller and J. W. Tukey.  Wiley.

  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis.}  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link[stats]{fivenum}}, \code{\link{boxplot}}, \code{\link{bxp}}.
}
\examples{
x <- c(1:100, 1000)
(b1 <- boxplot.stats(x))
(b2 <- boxplot.stats(x, do.conf=FALSE, do.out=FALSE))
stopifnot(b1 $ stats == b2 $ stats) # do.out=F is still robust
boxplot.stats(x, coef = 3, do.conf=FALSE)
## no outlier treatment:
boxplot.stats(x, coef = 0)

boxplot.stats(c(x, NA)) # slight change : n is 101
(r <- boxplot.stats(c(x, -1:1/0)))
stopifnot(r$out == c(1000, -Inf, Inf))

%% extended example (for the NG of Rdoc):
\dontshow{
 ## Difference between quartiles and hinges :
 nn <- 1:17 ;  n4 <- nn \%\% 4
 hin <- sapply(sapply(nn, seq), function(x) boxplot.stats(x)$stats[c(2,4)])
 q13 <- sapply(sapply(nn, seq), quantile, probs = c(1,3)/4, names = FALSE)
 m <- t(rbind(q13,hin))[, c(1,3,2,4)]
 dimnames(m) <- list(paste(nn), c("q1","lH", "q3","uH"))
 stopifnot(m[n4==1, 1:2] == (nn[n4==1] + 3)/4,# quart. = hinge
           m[n4==1, 3:4] == (3*nn[n4==1]+1)/4,
           m[,"lH"] == ( (nn+3) \%/\% 2) / 2,
           m[,"uH"] == ((3*nn+2)\%/\% 2) / 2)
 cm <- noquote(format(m))
 cm[m[,2] == m[,1], 2] <- " = "
 cm[m[,4] == m[,3], 4] <- " = "
 cm
}

}
\keyword{dplot}
\eof
\name{bxp}
\alias{bxp}
\title{Box Plots from Summaries}
\description{
  \code{bxp} draws box plots based on the given summaries in \code{z}.
  It is usually called from within \code{\link{boxplot}}, but can be
  invoked directly.
}
\usage{
bxp(z, notch = FALSE, width = NULL, varwidth = FALSE, outline = TRUE,
    notch.frac = 0.5, boxwex = 0.8, border = par("fg"), col = NULL,
    log = "", pars = NULL, frame.plot = axes, horizontal = FALSE,
    add = FALSE, at = NULL, show.names=NULL, \dots)
}
\arguments{
  \item{z}{a list containing data summaries to be used in constructing
    the plots.  These are usually the result of a call to
    \code{\link{boxplot}}, but can be generated in any fashion.}
  \item{notch}{if \code{notch} is \code{TRUE}, a notch is drawn in each
    side of the boxes.  If the notches of two plots do not overlap then
    the medians are significantly different at the 5 percent level.}
  \item{width}{a vector giving the relative widths of the boxes making
    up the plot.}
  \item{varwidth}{if \code{varwidth} is \code{TRUE}, the boxes are drawn
    with widths proportional to the square-roots of the number of
    observations in the groups.}
  \item{outline}{if \code{outline} is not true, the boxplot lines are
    not drawn.}
  \item{boxwex}{a scale factor to be applied to all boxes.  When there
    are only a few groups, the appearance of the plot can be improved by
    making the boxes narrower.}
  \item{notch.frac}{numeric in (0,1). When \code{notch=TRUE}, the
    fraction of the box width that the notches should use.}
  \item{border}{character or numeric (vector), the color of the box
    borders.  Is recycled for multiple boxes.}
  \item{col}{character or numeric; the color within the box.  Is
    recycled for multiple boxes}
  \item{log}{character, indicating if any axis should be drawn in
    logarithmic scale, as in \code{\link{plot.default}}.}
  \item{frame.plot}{logical, indicating if a \dQuote{frame}
    (\code{\link{box}}) should be drawn; defaults to \code{TRUE}, unless
    \code{axes = FALSE} is specified.}
  \item{horizontal}{logical indicating if the  boxplots should be
    horizontal; default \code{FALSE} means vertical boxes.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots
    should be drawn, particularly when \code{add = TRUE}; defaults to
    \code{1:n} where \code{n} is the number of boxes.}
  \item{show.names}{Set to \code{TRUE} or \code{FALSE} to override the
    defaults on whether an x-axis label is printed for each group.}
  \item{pars,\dots}{graphical parameters can be passed as arguments to
    this function, either as a list (\code{pars}) or
    normally(\code{\dots}).

    Currently, \code{pch}, \code{cex}, and \code{bg} are passed to
    \code{\link{points}},\cr
    \code{ylim} and \code{axes} to the main plot
    (\code{\link{plot.default}}), \code{xaxt}, \code{yaxt}, \code{las}
    to \code{\link{axis}} and the others to \code{\link{title}}.
  }
}
\value{
  An invisible vector, actually identical to the \code{at} argument,
  with the coordinates ("x" if horizontal is false, "y" otherwise) of
  box centers, useful for adding to the plot.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
set.seed(753)
(bx.p <- boxplot(split(rt(100, 4), gl(5,20))))
op <- par(mfrow= c(2,2))
bxp(bx.p, xaxt = "n")
bxp(bx.p, notch = TRUE, axes = FALSE, pch = 4, col=1:5)
bxp(bx.p, notch = TRUE, col= "lightblue", frame= FALSE, outl= FALSE,
    main = "bxp(*, frame= FALSE, outl= FALSE)")
bxp(bx.p, notch = TRUE, col= "lightblue", border= 2:6, ylim = c(-4,4),
    pch = 22, bg = "green", log = "x", main = "... log='x', ylim=*")
par(op)
op <- par(mfrow= c(1,2))
data(PlantGrowth)
## single group -- no label
boxplot (weight~group, data=PlantGrowth, subset=group=="ctrl")
## with label
bx<-boxplot(weight~group, data=PlantGrowth, subset=group=="ctrl",plot=FALSE)
bxp(bx,show.names=TRUE)
par(op)
}
\keyword{aplot}
\eof
\name{check.options}
\alias{check.options}
\title{Set Options with Consistency Checks}
\usage{
check.options(new, name.opt, reset = FALSE, assign.opt = FALSE,
              envir = .GlobalEnv, check.attributes = c("mode", "length"),
              override.check = FALSE)
}
\description{
  Utility function for setting options with some consistency checks.
  The \code{\link{attributes}} of the new settings in \code{new} are
  checked for consistency with the \emph{model} (often default)
  list in \code{name.opt}.
}
\arguments{
  \item{new}{a \emph{named} list}
  \item{name.opt}{character with the name of \R object containing the
    \dQuote{model} (default) list.}
  \item{reset}{logical; if \code{TRUE}, reset the options from
    \code{name.opt}.  If there is more than one \R object with name
    \code{name.opt}, remove the first one in the \code{\link{search}()} path.}
  \item{assign.opt}{logical; if \code{TRUE}, assign the \ldots}
  \item{envir}{the \code{\link{environment}} used for \code{\link{get}}
    and \code{\link{assign}}.}
  \item{check.attributes}{character containing the attributes which
    \code{check.options} should check.}
  \item{override.check}{logical vector of length \code{length(new)} (or 1
    which entails recycling).
    For those \code{new[i]} where \code{override.check[i] == TRUE}, the
    checks are overriden and the changes made anyway.}
}
%% Source in ../R/postscript.R
\value{
  A list of components with the same names as the one called
  \code{name.opt}.
  The values of the components are changed from the \code{new} list,
  as long as these pass the checks (when these are not overridden
  according to \code{override.check}).
}
\author{Martin Maechler}
\seealso{\code{\link{ps.options}} which uses \code{check.options}.}
% 
\examples{
(L1 <- list(a=1:3, b=pi, ch="CH"))
check.options(list(a=0:2), name.opt = "L1")
check.options(NULL, reset = TRUE, name.opt = "L1")
}
\keyword{utilities}
\keyword{programming}
\eof
\name{col2rgb}
\alias{col2rgb}
\title{Color to RGB Conversion}
\description{
  \dQuote{Any \R color} to RGB (red/green/blue) conversion.
}
\usage{
col2rgb(col)
}
\arguments{
  \item{col}{vector of any of the three kind of \R colors, i.e., either
    a color name (an element of \code{\link{colors}()}), a hexadecimal
    string of the form \code{"#rrggbb"}, or an integer \code{i} meaning
    \code{palette()[i]}.}
}
\details{
  For integer colors, \code{0} is shorthand for the current
  \code{par("bg")}, and \code{\link{NA}} means \dQuote{nothing} which
  effectively does not draw the corresponding item.

  For character colors, \code{"NA"} is equivalent to \code{NA} above.
}
\value{
  an integer matrix with three rows and number of columns the length
  (and names if any) as \code{col}.
}
\author{Martin Maechler}
\seealso{\code{\link{rgb}}, \code{\link{colors}}, \code{\link{palette}}, etc.}
\examples{
col2rgb("peachpuff")
col2rgb(c(blu = "royalblue", reddish = "tomato")) # names kept

col2rgb(1:8)# the ones from the palette() :

col2rgb(paste("gold", 1:4, sep=""))

col2rgb("#08a0ff")
## all three kind of colors mixed :
col2rgb(c(red="red", palette= 1:3, hex="#abcdef"))

##-- NON-INTRODUCTORY examples --

grC <- col2rgb(paste("gray",0:100,sep=""))
table(print(diff(grC["red",])))# '2' or '3': almost equidistant
## The 'named' grays are in between {"slate gray" is not gray, strictly}
col2rgb(c(g66="gray66", darkg= "dark gray", g67="gray67",
          g74="gray74", gray =      "gray", g75="gray75",
          g82="gray82", light="light gray", g83="gray83"))

crgb <- col2rgb(cc <- colors())
colnames(crgb) <- cc
t(crgb)## The whole table

ccodes <- c(256^(2:0) \%*\% crgb)## = internal codes
## How many names are 'aliases' of each other:
table(tcc <- table(ccodes))
length(uc <- unique(sort(ccodes))) # 502
## All the multiply named colors:
mult <- uc[tcc >= 2]
cl <- lapply(mult, function(m) cc[ccodes == m])
names(cl) <- apply(col2rgb(sapply(cl, function(x)x[1])),
                   2, function(n)paste(n, collapse=","))
utils::str(cl)
\dontrun{
 if(require(xgobi)) { ## Look at the color cube dynamically :
   tc <- t(crgb[, !duplicated(ccodes)])
   table(is.gray <- tc[,1] == tc[,2] & tc[,2] == tc[,3])# (397, 105)
   xgobi(tc, color = c("gold", "gray")[1 + is.gray])
 }
}
}
\keyword{color}
\keyword{dplot}
\eof
\name{colors}
\alias{colors}
\alias{colours}
\title{Color Names}
\description{
  Returns the built-in color names which \R knows about.
}
\usage{
colors()
}
\details{
  These color names can be used with a \code{col=} specification in
  graphics functions.

  An even wider variety of colors can be created with primitives
  \code{rgb} and \code{hsv} or the derived \code{rainbow},
  \code{heat.colors}, etc.
}
\value{
  A character vector containing all the built-in color names.
}
\seealso{
  \code{\link{palette}} for setting the \dQuote{palette} of colors for
  \code{par(col=}\emph{<num>}\code{)};
  \code{\link{rgb}}, \code{\link{hsv}}, \code{\link{gray}};
  \code{\link{rainbow}} for a nice example;
  and \code{\link{heat.colors}}, \code{\link{topo.colors}} for images.

  \code{\link{col2rgb}} for translating to RGB numbers and extended
  examples.
}
\examples{
cl <- colors()
length(cl); cl[1:20]
}
\keyword{color}
\keyword{dplot}
\keyword{sysdata}
\eof
\name{contour}
\alias{contour}
\alias{contour.default}
\alias{contourLines}
\title{Display Contours}
\description{
  Create a contour plot, or add contour lines to an existing plot.
}
\usage{
contour(x, \dots)
\method{contour}{default}(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)),
        z,
        nlevels = 10, levels = pretty(zlim, nlevels), labels = NULL,
        xlim = range(x, finite = TRUE),
        ylim = range(y, finite = TRUE),
        zlim = range(z, finite = TRUE),
        labcex = 0.6, drawlabels = TRUE, method = "flattest",
	vfont = c("sans serif", "plain"),
        axes = TRUE, frame.plot = axes,
        col = par("fg"), lty = par("lty"), lwd = par("lwd"),
	add = FALSE, \dots)
contourLines(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)),
	     z, nlevels = 10, levels = pretty(range(z, na.rm=TRUE), nlevels))
}
\arguments{
  \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{nlevels}{number of contour levels desired \bold{iff}
    \code{levels} is not supplied.}
  \item{levels}{numeric vector of levels at which to draw contour
    lines.}
  \item{labels}{a vector giving the labels for the contour lines.  If
    \code{NULL} then the levels are used as labels.}
  \item{labcex}{\code{cex} for contour labelling.}
  \item{drawlabels}{logical.  Contours are labelled if \code{TRUE}.}
  \item{method}{character string specifying where the labels will be
    located. Possible values are \code{"simple"}, \code{"edge"} and
    \code{"flattest"} (the default). See the Details section.}
  \item{vfont}{if a character vector of length 2 is specified, then Hershey
    vector fonts are used for the contour labels.
    The first element of the vector
    selects a typeface and the second element selects a fontindex
    (see \code{\link{text}} for more information).}
  \item{xlim, ylim, zlim}{x-, y- and z-limits for the plot.}
  \item{axes, frame.plot}{logical indicating whether axes or a box
    should be drawn, see \code{\link{plot.default}}.}
  \item{col}{color for the lines drawn.}
  \item{lty}{line type for the lines drawn.}
  \item{lwd}{line width for the lines drawn.}
  \item{add}{logical. If \code{TRUE}, add to a current plot.}
  \item{\dots}{additional graphical parameters (see \code{\link{par}}).
    The plot aspect ratio \code{asp} (see \code{\link{plot.window}}) 
    and the arguments to \code{\link{title}} may also be supplied.}
}
\details{
  \code{contour} is a generic function with only a default method in
  base \R.

  \code{contourLines} draws nothing, but returns a set of contour lines.
  
  There is currently no documentation about the algorithm.
  The source code is in \file{\$R\_HOME/src/main/plot3d.c}.

  The methods for positioning the labels on contours are \code{"simple"}
  (draw at the edge of the plot, overlaying the contour line),
  \code{"edge"} (draw at the edge of the plot, embedded in the contour
  line, with no labels overlapping) and \code{"flattest"}
  (draw on the flattest section of the contour, embedded in the
  contour line, with no labels overlapping).  The second and third may
  not draw a label on every contour line.

  For information about vector fonts, see the
  help for \code{\link{text}} and \code{\link{Hershey}}.
}
\value{
  \code{contourLines} returns a list of contours.
  Each contour is a list with elements:
  \item{level }{The contour level.}
  \item{x }{The x-coordinates of the contour.}
  \item{y }{The y-coordinates of the contour.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{filled.contour}} for \dQuote{color-filled} contours,
  \code{\link{image}} and the graphics demo which can be invoked as
  \code{demo(graphics)}.
}
\examples{
x <- -6:16
op <- par(mfrow = c(2, 2))
contour(outer(x, x), method = "edge", vfont = c("sans serif", "plain"))
z <- outer(x, sqrt(abs(x)), FUN = "/")
## Should not be necessary:
z[!is.finite(z)] <- NA
image(x, x, z)
contour(x, x, z, col = "pink", add = TRUE, method = "edge",
	vfont = c("sans serif", "plain"))
contour(x, x, z, ylim = c(1, 6), method = "simple", labcex = 1)
contour(x, x, z, ylim = c(-6, 6), nlev = 20, lty = 2, method = "simple")
par(op)

## Persian Rug Art:
x <- y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))
opar <- par(mfrow = c(2, 2), mar = rep(0, 4))
for(f in pi^(0:3))
  contour(cos(r^2)*exp(-r/f),
          drawlabels = FALSE, axes = FALSE, frame = TRUE)

data("volcano")
rx <- range(x <- 10*1:nrow(volcano))
ry <- range(y <- 10*1:ncol(volcano))
ry <- ry + c(-1,1) * (diff(rx) - diff(ry))/2
tcol <- terrain.colors(12)
par(opar); opar <- par(pty = "s", bg = "lightcyan")
plot(x = 0, y = 0,type = "n", xlim = rx, ylim = ry, xlab = "", ylab = "")
u <- par("usr")
rect(u[1], u[3], u[2], u[4], col = tcol[8], border = "red")
contour(x, y, volcano, col = tcol[2], lty = "solid", add = TRUE,
	vfont = c("sans serif", "plain"))
title("A Topographic Map of Maunga Whau", font = 4)
abline(h = 200*0:4, v = 200*0:4, col = "lightgray", lty = 2, lwd = 0.1)

## contourLines produces the same contour lines as contour
line.list <- contourLines(x, y, volcano)
plot(x = 0, y = 0,type = "n", xlim = rx, ylim = ry, xlab = "", ylab = "")
u <- par("usr")
rect(u[1], u[3], u[2], u[4], col = tcol[8], border = "red")
contour(x, y, volcano, col = tcol[2], lty = "solid", add = TRUE,
             vfont = c("sans serif", "plain"))
templines <- function(clines) {
  lines(clines[[2]], clines[[3]])
}  
invisible(lapply(line.list, templines))
par(opar)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{coplot}
\title{Conditioning Plots}
\usage{
coplot(formula, data, given.values, panel = points, rows, columns,
       show.given = TRUE, col = par("fg"), pch = par("pch"), 
       bar.bg = c(num = gray(0.8), fac = gray(0.95)),
       xlab = c(x.name, paste("Given :", a.name)),
       ylab = c(y.name, paste("Given :", b.name)),
       subscripts = FALSE,
       axlabels = function(f) abbreviate(levels(f)),
       number = 6, overlap = 0.5, xlim, ylim, \dots) 
co.intervals(x, number = 6, overlap = 0.5)
}
\alias{coplot}
\alias{co.intervals}
\arguments{
  \item{formula}{a formula describing the form of conditioning plot.  A
    formula of the form \code{y ~ x | a} indicates that plots of
    \code{y} versus \code{x} should be produced conditional on the
    variable \code{a}.  A formula of the form \code{y ~ x| a * b}
    indicates that plots of \code{y} versus \code{x} should be produced
    conditional on the two variables \code{a} and \code{b}.

    All three or four variables may be either numeric or factors.
    When \code{x} or \code{y} are factors, the result is almost as if
    \code{as.numeric()} was applied, whereas for factor
    \code{a} or \code{b}, the conditioning (and its graphics if
    \code{show.given} is true) are adapted.
  }
  \item{data}{a data frame containing values for any variables in the
    formula.  By default the environment where \code{coplot} was called
    from is used.}
  \item{given.values}{a value or list of two values which determine how
    the conditioning on \code{a} and \code{b} is to take place.

    When there is no \code{b} (i.e., conditioning only on \code{a}),
    usually this is a matrix with two columns each row of which gives an
    interval, to be conditioned on, but is can also be a single vector
    of numbers or a set of factor levels (if the variable being
    conditioned on is a factor). In this case (no \code{b}),
    the result of \code{co.intervals} can be used directly as
    \code{given.values} argument.
  }
  \item{panel}{a \code{\link{function}(x, y, col, pch, \dots)}
      which gives the action to be carried out in
      each panel of the display.  The default is \code{points}.}
  \item{rows}{the panels of the plot are laid out in a \code{rows} by
    \code{columns} array.  \code{rows} gives the number of rows in the
    array.}
  \item{columns}{the number of columns in the panel layout array.}
  \item{show.given}{logical (possibly of length 2 for 2 conditioning
      variables): should conditioning plots be shown for the
    corresponding conditioning variables (default \code{TRUE})}.
  \item{col}{a vector of colors to be used to plot the points.  If too
    short, the values are recycled.}
  \item{pch}{a vector of plotting symbols or characters.  If too short,
    the values are recycled.}
  \item{bar.bg}{a named vector with components \code{"num"} and
    \code{"fac"} giving the background colors for the (shingle) bars,
    for \bold{num}eric and \bold{fac}tor conditioning variables respectively.}
  \item{xlab}{character; labels to use for the x axis and the
    first conditioning variable.  If only one label is given, it is used
    for the x axis and the default label is used for the conditioning
    variable.}
  \item{ylab}{character; labels to use for the y axis and any
    second conditioning variable.}
  \item{subscripts}{logical: if true the panel function is given an
    additional (third) argument \code{subscripts} giving the subscripts
    of the data passed to that panel.}
  \item{axlabels}{function for creating axis (tick) labels when x or y
      are factors.}
  \item{number}{integer; the number of conditioning intervals,
    for a and b, possibly of length 2.  It is only used if the
    corresponding conditioning variable is not a \code{\link{factor}}.}
  \item{overlap}{numeric < 1; the fraction of overlap of the
    conditioning variables, possibly of length 2 for x and y
    direction.  When overlap < 0, there will be \emph{gaps} between
    the data slices.}
  \item{xlim}{the range for the x axis.}
  \item{ylim}{the range for the y axis.}
  \item{\dots}{additional arguments to the panel function.}

  \item{x}{a numeric vector.}
}
\description{
  This function produces two variants of the \bold{co}nditioning plots
  discussed in the reference below.
}
\details{
  In the case of a single conditioning variable \code{a}, when both
  \code{rows} and \code{columns} are unspecified, a \dQuote{close to
    square} layout is chosen with \code{columns >= rows}.

  In the case of multiple \code{rows}, the \emph{order} of the panel
  plots is from the bottom and from the left (corresponding to
  increasing \code{a}, typically).

  A panel function should not attempt to start a new plot, but just plot
  within a given coordinate system: thus \code{plot} and \code{boxplot}
  are not panel functions.
}
\value{
  \code{co.intervals(., number, .)} returns a (\code{number} \eqn{\times}{x}
  2) \code{\link{matrix}}, say \code{ci},  where \code{ci[k,]} is
  the \code{\link{range}} of \code{x} values for the \code{k}-th interval.
}
\references{
  Chambers, J. M. (1992)
  \emph{Data for models.}
  Chapter 3 of \emph{Statistical Models in S}
  eds J. M. Chambers and T. J. Hastie, Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1993) \emph{Visualizing Data.} New Jersey: Summit Press.
}
\seealso{
  \code{\link{pairs}},
  \code{\link{panel.smooth}},
  \code{\link{points}}.
}
\examples{
## Tonga Trench Earthquakes
data(quakes)
coplot(lat ~ long | depth, data = quakes)
given.depth <- co.intervals(quakes$depth, number=4, overlap=.1)
coplot(lat ~ long | depth, data = quakes, given.v=given.depth, rows=1)

## Conditioning on 2 variables:
ll.dm <- lat ~ long | depth * mag
coplot(ll.dm, data = quakes)
coplot(ll.dm, data = quakes, number=c(4,7), show.given=c(TRUE,FALSE))
coplot(ll.dm, data = quakes, number=c(3,7),
       overlap=c(-.5,.1)) # negative overlap DROPS values

data(warpbreaks)
## given two factors
Index <- seq(length=nrow(warpbreaks)) # to get nicer default labels
coplot(breaks ~ Index | wool * tension, data = warpbreaks, show.given = 0:1)
coplot(breaks ~ Index | wool * tension, data = warpbreaks,
       col = "red", bg = "pink", pch = 21, bar.bg = c(fac = "light blue"))

## Example with empty panels:
data(state)
attach(data.frame(state.x77))#> don't need 'data' arg. below
coplot(Life.Exp ~ Income | Illiteracy * state.region, number = 3,
       panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...))
## y ~ factor -- not really sensical, but 'show off':
coplot(Life.Exp ~ state.region | Income * state.division,
       panel = panel.smooth)
detach() # data.frame(state.x77)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{curve}
\title{Draw Function Plots}
\alias{curve}
\alias{plot.function}
\usage{
curve(expr, from, to, n = 101, add = FALSE, type = "l",
      ylab = NULL, log = NULL, xlim = NULL, \dots)

\method{plot}{function}(x, from = 0, to = 1, xlim = NULL, \dots)
}
\arguments{
  \item{expr}{an expression written as a function of \code{x}, or
    alternatively the name of a function which will be plotted.}
  \item{x}{a \sQuote{vectorizing} numeric \R function.}
  \item{from,to}{the range over which the function will be plotted.}
  \item{n}{integer; the number of x values at which to evaluate.}
  \item{add}{logical; if \code{TRUE} add to already existing plot.}
  \item{xlim}{numeric of length 2; if specified, it serves as default
    for \code{c(from, to)}.}
  \item{type, ylab, log, \dots}{graphical parameters can also be
    specified as arguments.
    \code{plot.function} passes all these to \code{curve}.}
}
\description{
  Draws a curve corresponding to the given function or expression (in
  \code{x}) over the interval \code{[from,to]}.
}
\details{
  The evaluation of \code{expr} is at \code{n} points equally spaced
  over the range \code{[from, to]}, possibly adapted to log scale.  The
  points determined in this way are then joined with straight lines.
  \code{x(t)} or \code{expr} (with \code{x} inside) must return a
  numeric of the same length as the argument \code{t} or \code{x}.

  If \code{add = TRUE}, \code{c(from,to)} default to \code{xlim} which
  defaults to the current x-limits.  Further, \code{log} is taken from the
  current plot when \code{add} is true.

  This used to be a quick hack which now seems to serve a useful purpose,
  but can give bad results for functions which are not smooth.

  For \dQuote{expensive} \code{expr}essions, you should use smarter tools.
}
\seealso{
  \code{\link[stats]{splinefun}} for spline interpolation, \code{\link{lines}}.
}
\examples{
op <- par(mfrow=c(2,2))
curve(x^3-3*x, -2, 2)
curve(x^2-2, add = TRUE, col = "violet")

plot(cos, xlim = c(-pi,3*pi), n = 1001, col = "blue")

chippy <- function(x) sin(cos(x)*exp(-x/2))
curve(chippy, -8, 7, n=2001)
curve(chippy, -8, -5)

for(ll in c("","x","y","xy"))
   curve(log(1+x), 1,100, log=ll, sub=paste("log= '",ll,"'",sep=""))
par(op)
}
\keyword{hplot}
\eof
\name{dev.xxx}
\title{Control Multiple Devices}
\usage{
dev.cur()
dev.list()
dev.next(which = dev.cur())
dev.prev(which = dev.cur())
dev.off(which = dev.cur())
dev.set(which = dev.next())
graphics.off()
}
\alias{dev.cur}
\alias{dev.list}
\alias{dev.next}
\alias{dev.prev}
\alias{dev.off}
\alias{dev.set}
\alias{graphics.off}

\arguments{
  \item{which}{An integer specifying a device number}
}
\description{
  These functions provide control over multiple graphics devices.

  Only one device is the \emph{active} device.  This is the device in
  which all graphics operations occur.

  Devices are associated with a name (e.g., \code{"X11"} or
  \code{"postscript"}) and a number; the \code{"null device"} is always
  device 1.

  \code{dev.off} shuts down the specified (by default the current) device.
  \code{graphics.off()} shuts down all open graphics devices.

  \code{dev.set} makes the specified device the active device.
}
\value{
  \code{dev.cur} returns the number and name of the active device,
  or 1, the null device, if none is active.

  \code{dev.list} returns the numbers of all open devices, except device
  1, the null device.  This is a numeric vector with a names attribute
  giving the names, or \code{NULL} is there is no open device.

  \code{dev.next} and \code{dev.prev} return the number and name of the
  next / previous device in the list of devices.  The list is regarded as
  a circular list, and \code{"null device"} will be included only if there
  are no open devices.

  \code{dev.off} returns the name and number of the new active device
  (after the specified device has been shut down).

  \code{dev.set} returns the name and number of the new active device.
}
\seealso{
  \code{\link{Devices}}, such as \code{\link{postscript}}, etc;
  \code{\link{layout}} and its links for setting up plotting regions
  on the current device.
}
\examples{
\dontrun{## Unix-specific example
x11()
plot(1:10)
x11()
plot(rnorm(10))
dev.set(dev.prev())
abline(0,1)# through the 1:10 points
dev.set(dev.next())
abline(h=0, col="gray")# for the residual plot
dev.set(dev.prev())
dev.off(); dev.off()#- close the two X devices
}
}
\keyword{device}
\keyword{iplot}
\eof
\name{dev2}
\alias{dev.copy}
\alias{dev.print}
\alias{dev.copy2eps}
\alias{dev.control}
\title{Copy Graphics Between Multiple Devices}
\usage{
dev.copy(device, \dots, which = dev.next())
dev.print(device = postscript, \dots)
dev.copy2eps(\dots)
dev.control(displaylist = c("inhibit", "enable"))
}
\arguments{
  \item{device}{A device function (e.g., \code{x11},
    \code{postscript}, \ldots)}
  \item{\dots}{Arguments to the \code{device} function above.
    For \code{dev.print}, this includes \code{which} and by default any
    \code{\link{postscript}} arguments.}
  \item{which}{A device number specifying the device to copy to}
  \item{displaylist}{A character string: the only valid values are
    \code{"inhibit"} and \code{"enable"}.}
}
\description{
  \code{dev.copy} copies the graphics contents of the current device
  to the device specified by \code{which} or to a new device which has
  been created by the function specified by \code{device} (it is an
  error to specify both \code{which} and \code{device}).  (If recording
  is off on the current device, there are no contents to copy: this will
  result in no plot or an empty plot.)
  The device copied to becomes the current device.

  \code{dev.print} copies the graphics contents of the current device
  to a new device which has been created by the function specified by
  \code{device} and then shuts the new device.

  \code{dev.copy2eps} is similar to \code{dev.print} but produces an
  EPSF output file, in portrait orientation (\code{horizontal = FALSE})

  \code{dev.control} allows the user to control the recording of
  graphics operations in a device.  If \code{displaylist} is \code{"inhibit"}
  (\code{"enable")} then recording is turned off (on). It is only safe
  to change this at the beginning of a plot (just before or just after a
  new page).  Initially recording is on for screen devices, and off for
  print devices.
}
\value{
  \code{dev.copy} returns the name and number of the device which has
  been copied to.

  \code{dev.print} and \code{dev.copy2eps} return the name and number of
  the device which has been copied from.
}
\details{
  For \code{dev.copy2eps}, \code{width} and \code{height} are taken
  from the current device unless otherwise specified.  If just one of
  \code{width} and \code{height} is specified, the other is adjusted
  to preserve the aspect ratio of the device being copied.  The default
  file name is \code{Rplot.eps}.

#ifdef unix
  The default for \code{dev.print} is to produce and print a postscript
  copy, if \code{\link{options}("printcmd")} is set suitably.
#endif
#ifdef windows
  The default for \code{dev.print} is to produce and print a postscript
  copy.  This will not work unless
  \code{\link{options}("printcmd")} is set suitably and you have a
  PostScript printer: see \code{\link{postscript}} for how to set this
  up.  Windows users may prefer to use \code{dev.print(win.print)}.
#endif


  \code{dev.print} is most useful for producing a postscript print
  (its default) when the following applies.  Unless
  \code{file} is specified, the plot will be printed.  Unless
  \code{width}, \code{height} and \code{pointsize} are specified
  the plot dimensions will be taken from the current device, shrunk
  if necessary to fit on the paper. (\code{pointsize} is rescaled if the
  plot is shrunk.)  If \code{horizontal} is not specified and the plot
  can be printed at full size by switching its value this is done
  instead of shrinking the plot region.

  If \code{dev.print} is used with a specified device (even
  \code{postscript}) it sets the width and height in the same way as
  \code{dev.copy2eps}.
}
\note{
  Most devices (including all screen devices) have a display list
  which records all of the graphics operations that occur in the device.
  \code{dev.copy} copies graphics contents by copying the display list
  from one device to another device.  Also, automatic redrawing of
  graphics contents following the resizing of a device depends on the
  contents of the display list.

  After the command \code{dev.control("inhibit")}, graphics operations
  are not recorded in the display list so that \code{dev.copy} and
  \code{dev.print} will not copy anything and the contents of a device
  will not be redrawn automatically if the device is resized.

  The recording of graphics operations is relatively expensive in
  terms of memory so the command \code{dev.control("inhibit")} can be
  useful if memory usage is an issue.
}
\seealso{
  \code{\link{dev.cur}} and other \code{dev.xxx} functions
}
\examples{
\dontrun{
x11()
plot(rnorm(10), main="Plot 1")
dev.copy(device=x11)
mtext("Copy 1", 3)
dev.print(width=6, height=6, horizontal=FALSE) # prints it
dev.off(dev.prev())
dev.off()
}
}
\keyword{device}
\eof
\name{dev2bitmap}
\alias{dev2bitmap}
\alias{bitmap}
\title{Graphics Device for Bitmap Files via GhostScript}
\usage{
bitmap(file, type = "png256", height = 6, width = 6, res = 72,
       pointsize, \dots)
dev2bitmap(file, type = "png256", height = 6, width = 6, res = 72,
           pointsize, \dots)
}
\arguments{
  \item{file}{The output file name, with an appropriate extension.}
  \item{type}{The type of bitmap. the default is \code{"png256"}.}
  \item{height}{The plot height, in inches.}
  \item{width}{The plot width, in inches.}
  \item{res}{Resolution, in dots per inch.}
  \item{pointsize}{The pointsize to be used for text: defaults to
    something reasonable given the width and height}
  \item{\dots}{Other parameters passed to \code{\link{postscript}}.}
}
\description{
  \code{bitmap} generates a graphics file.
  \code{dev2bitmap} copies the current graphics device to a file in a
  graphics format.
}
\details{
  \code{dev2bitmap} works by copying the current device to a
  \code{\link{postscript}} device, and post-processing the output file
  using \code{ghostscript}.  \code{bitmap} works in the same way using a
  \code{postscript} device and postprocessing the output as
  \dQuote{printing}.

  You will need a version of \code{ghostscript} (5.10 and
  later have been tested): the full path to the executable can be set by
  the environment variable \env{R\_GSCMD}.

  The types available will depend on the version of \code{ghostscript},
  but are likely to include
  \code{"pcxmono"}, \code{"pcxgray"}, \code{"pcx16"}, \code{"pcx256"},
  \code{"pcx24b"}, \code{"pcxcmyk"}, \code{"pbm"}, \code{"pbmraw"},
  \code{"pgm"}, \code{"pgmraw"}, \code{"pgnm"}, \code{"pgnmraw"},
  \code{"pnm"}, \code{"pnmraw"}, \code{"ppm"}, \code{"ppmraw"},
  \code{"pkm"}, \code{"pkmraw"}, \code{"tiffcrle"}, \code{"tiffg3"},
  \code{"tiffg32d"}, \code{"tiffg4"}, \code{"tifflzw"},
  \code{"tiffpack"}, \code{"tiff12nc"}, \code{"tiff24nc"},
  \code{"psmono"}, \code{"psgray"}, \code{"psrgb"}, \code{"bit"},
  \code{"bitrgb"}, \code{"bitcmyk"}, \code{"pngmono"}, \code{"pnggray"},
  \code{"png16"}, \code{"png256"}, \code{"png16m"}, \code{"jpeg"},
  \code{"jpeggray"}, \code{"pdfwrite"}.

  Note: despite the name of the functions they can produce PDF \emph{via}
  \code{type = "pdfwrite"}, and the PDF produced is not bitmapped.

  For formats which contain a single image, a file specification like
  \code{Rplots\%03d.png} can be used: this is interpreted by GhostScript.

  For \code{dev2bitmap} if just one of \code{width} and \code{height} is
  specified, the other is chosen to preserve aspect ratio of the
  device being copied.
}
\value{
  None.
}

#ifdef windows
\note{
  Use of \code{bitmap} will leave a temporary file (with file name
  starting \code{Rbit}).  Use of the \code{\link{pdf}}, \code{\link{bmp}},
  \code{\link{png}} and \code{\link{jpeg}} devices is preferable to
  using these functions.
}
#endif

\seealso{
  \code{\link{postscript}}, \code{\link{png}} and
  \code{\link{jpeg}} and on Windows \code{bmp}.

  \code{\link{pdf}} generate PDF directly.

  To display an array of data, see \code{\link{image}}.
}

\keyword{utilities}
\eof
\name{dotchart}
\alias{dotchart}
\title{Cleveland Dot Plots}
\description{
  Draw a Cleveland dot plot.
}
\usage{
dotchart(x, labels = NULL, groups = NULL, gdata = NULL,
         cex = par("cex"), pch = 21, gpch = 21, bg = par("bg"),
         color = par("fg"), gcolor = par("fg"), lcolor = "gray",
         xlim = range(x[is.finite(x)]),
         main = NULL, xlab = NULL, ylab = NULL, \dots)
}
\arguments{
  \item{x}{either a vector or matrix of numeric values (\code{NA}s are
    allowed).  If \code{x} is a matrix the overall plot consists of
    juxtaposed dotplots for each row.}
  \item{labels}{a vector of labels for each point.
    For vectors the default is to use \code{names(x)} and for matrices
    the row labels \code{dimnames(x)[[1]]}.}
  \item{groups}{an optional factor indicating how the elements of
    \code{x} are grouped.
    If \code{x} is a matrix, \code{groups} will default to the columns
    of \code{x}.}
  \item{gdata}{data values for the groups.
    This is typically a summary such as the median or mean
    of each group.}
  \item{cex}{the character size to be used.  Setting \code{cex}
    to a value smaller than one can be a useful way of avoiding label
    overlap.}
  \item{pch}{the plotting character or symbol to be used.}
  \item{gpch}{the plotting character or symbol to be used for group
    values.}
  \item{bg}{the background color of plotting characters or symbols to be
    used; use \code{\link{par}(bg= *)} to set the background color of
    the whole plot.}
  \item{color}{the color(s) to be used for points an labels.}
  \item{gcolor}{the single color to be used for group labels and
    values.}
  \item{lcolor}{the color(s) to be used for the horizontal lines.}
  \item{xlim}{horizontal range for the plot, see
    \code{\link{plot.window}}, e.g.}
  \item{main}{overall title for the plot, see \code{\link{title}}.}
  \item{xlab, ylab}{axis annotations as in \code{title}.}
  \item{\dots}{graphical parameters can also be specified as arguments.}
}
\value{
  This function is invoked for its side effect, which is to produce two
  variants of dotplots as described in Cleveland (1985).

  Dot plots are a reasonable substitute for bar plots.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, CA: Wadsworth.
}
\examples{
data(VADeaths)
dotchart(VADeaths, main = "Death Rates in Virginia - 1940")
op <- par(xaxs="i")# 0 -- 100\%
dotchart(t(VADeaths), xlim = c(0,100),
         main = "Death Rates in Virginia - 1940")
par(op)
}
\keyword{hplot}
\eof
\name{filled.contour}
\alias{filled.contour}
\title{Level (Contour) Plots}
\usage{
filled.contour(x = seq(0, 1, len = nrow(z)),
               y = seq(0, 1, len = ncol(z)),
               z,
               xlim = range(x, finite=TRUE),
               ylim = range(y, finite=TRUE),
               zlim = range(z, finite=TRUE),
               levels = pretty(zlim, nlevels), nlevels = 20,
               color.palette = cm.colors,
               col = color.palette(length(levels) - 1),
               plot.title, plot.axes, key.title, key.axes,
               asp = NA, xaxs = "i", yaxs = "i", las = 1,
               axes = TRUE, frame.plot = axes, \dots)
}
\arguments{
 \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
 \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
 \item{xlim}{x limits for the plot.}
 \item{ylim}{y limits for the plot.}
 \item{zlim}{z limits for the plot.}
 \item{levels}{a set of levels which are used to partition the range
    of \code{z}.  Must be \bold{strictly} increasing (and finite).  Areas
    with \code{z} values between consecutive levels are painted with the
    same color.}
 \item{nlevels}{if \code{levels} is not specified, the range of \code{z},
    values is divided into approximately this many levels.}
 \item{color.palette}{a color palette function to be used to assign
    colors in the plot.}
 \item{col}{an explicit set of colors to be used in the plot.
    This argument overrides any palette function specification.}
 \item{plot.title}{statements which add titles to the main plot.}
 \item{plot.axes}{statements which draw axes (and a \code{\link{box}})
   on the main plot.  This overrides the default axes.}
 \item{key.title}{statements which add titles for the plot key.}
 \item{key.axes}{statements which draw axes on the plot key.
    This overrides the default axis.}
 \item{asp}{the \eqn{y/x} aspect ratio, see \code{\link{plot.window}}.}
 \item{xaxs}{the x axis style.  The default is to use internal
    labeling.}
 \item{yaxs}{the y axis style.  The default is to use internal
    labeling.}
 \item{las}{the style of labeling to be used.  The default is to
    use horizontal labeling. }
 \item{axes, frame.plot}{logicals indicating if axes and a box should be
   drawn, as in \code{\link{plot.default}}.}
 \item{\dots}{additional graphical parameters, currently only passed to
   \code{\link{title}()}.}
}
\description{
  This function produces a contour plot with the areas between the
  contours filled in solid color (Cleveland calls this a level plot).  A
  key showing how the colors map to z values is shown to the right of
  the plot.
}
\references{
  Cleveland, W. S. (1993)
  \emph{Visualizing Data}.
  Summit, New Jersey: Hobart.
}
\author{Ross Ihaka.}
\note{
  This function currently uses the \code{layout} function and so is
  restricted to a full page display.  As an alternative consider the
  \code{\link[lattice]{levelplot}} function from the \pkg{lattice}
  package which works in multipanel displays.

  The output produced by \code{filled.contour} is actually a combination
  of two plots; one is the filled contour and one is the legend.  Two
  separate coordinate systems are set up for these two plots, but they
  are only used internally - once the function has returned these
  coordinate systems are lost.  If you want to annotate the main contour
  plot, for example to add points, you can specify graphics commands in
  the \code{plot.axes} argument.  An example is given below.
}
\seealso{\code{\link{contour}}, \code{\link{image}},
  \code{\link{palette}}; \code{\link[lattice]{levelplot}} from package
  \pkg{lattice}.}
\examples{
data(volcano)
filled.contour(volcano, color = terrain.colors, asp = 1)# simple

x <- 10*1:nrow(volcano)
y <- 10*1:ncol(volcano)
filled.contour(x, y, volcano, color = terrain.colors,
    plot.title = title(main = "The Topography of Maunga Whau",
    xlab = "Meters North", ylab = "Meters West"),
    plot.axes = { axis(1, seq(100, 800, by = 100))
                  axis(2, seq(100, 600, by = 100)) },
    key.title = title(main="Height\n(meters)"),
    key.axes = axis(4, seq(90, 190, by = 10)))# maybe also asp=1
mtext(paste("filled.contour(.) from", R.version.string),
      side = 1, line = 4, adj = 1, cex = .66)

# Annotating a filled contour plot
a <- expand.grid(1:20, 1:20)
b <- matrix(a[,1] + a[,2], 20)
filled.contour(x = 1:20, y = 1:20, z = b,
               plot.axes={ axis(1); axis(2); points(10,10) })

## Persian Rug Art:
x <- y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))
filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)
## rather, the key *should* be labeled:
filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE, plot.axes = {})
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{fourfoldplot}
\alias{fourfoldplot}
\title{Fourfold Plots}
\description{
  Creates a fourfold display of a 2 by 2 by \eqn{k} contingency table on
  the current graphics device, allowing for the visual inspection of the
  association between two dichotomous variables in one or several
  populations (strata).
}
\usage{
fourfoldplot(x, color = c("#99CCFF", "#6699CC"), conf.level = 0.95,
             std = c("margins", "ind.max", "all.max"),
             margin = c(1, 2), space = 0.2, main = NULL,
             mfrow = NULL, mfcol = NULL)
}
\arguments{
  \item{x}{a 2 by 2 by \eqn{k} contingency table in array form, or as a
    2 by 2 matrix if \eqn{k} is 1.}
  \item{color}{a vector of length 2 specifying the colors to use for the
    smaller and larger diagonals of each 2 by 2 table.}
  \item{conf.level}{confidence level used for the confidence rings on
    the odds ratios.  Must be a single nonnegative number less than 1;
    if set to 0, confidence rings are suppressed.}
  \item{std}{a character string specifying how to standardize the table.
    Must be one of \code{"margins"}, \code{"ind.max"}, or
    \code{"all.max"}, and can be abbreviated by the initial letter.
    If set to \code{"margins"}, each 2 by 2 table is standardized to
    equate the margins specified by \code{margin} while preserving the
    odds ratio.  If \code{"ind.max"} or \code{"all.max"}, the tables are
    either individually or simultaneously standardized to a maximal cell
    frequency of 1.}
  \item{margin}{a numeric vector with the margins to equate.  Must be
    one of \code{1}, \code{2}, or \code{c(1, 2)} (the default), which
    corresponds to standardizing the row, column, or both margins in
    each 2 by 2 table.
    Only used if \code{std} equals \code{"margins"}.}
  \item{space}{the amount of space (as a fraction of the maximal radius
    of the quarter circles) used for the row and column lebals.}
  \item{main}{character string for the fourfold title.}
  \item{mfrow}{a numeric vector of the form \code{c(nr, nc)}, indicating
    that the displays for the 2 by 2 tables should be arranged in an
    \code{nr} by \code{nc} layout, filled by rows.}
  \item{mfcol}{a numeric vector of the form \code{c(nr, nc)}, indicating
    that the displays for the 2 by 2 tables should be arranged in an
    \code{nr} by \code{nc} layout, filled by columns.}
}
\details{
  The fourfold display is designed for the display of 2 by 2 by \eqn{k}
  tables.

  Following suitable standardization, the cell frequencies
  \eqn{f_{ij}}{f[i,j]} of each 2 by 2 table are shown as a quarter
  circle whose radius is proportional to
  \eqn{\sqrt{f_{ij}}}{sqrt(f[i,j])} so that its area is proportional to
  the cell frequency.  An association (odds ratio different from 1)
  between the binary row and column variables is indicated by the
  tendency of diagonally opposite cells in one direction to differ in
  size from those in the other direction; color is used to show this
  direction.  Confidence rings for the odds ratio allow a visual test of
  the null of no association; the rings for adjacent quadrants overlap
  iff the observed counts are consistent with the null hypothesis.

  Typically, the number \eqn{k} corresponds to the number of levels of a
  stratifying variable, and it is of interest to see whether the
  association is homogeneous across strata.  The fourfold display
  visualizes the pattern of association.  Note that the confidence rings
  for the individual odds ratios are not adjusted for multiple testing.
}
\references{
  Friendly, M. (1994).
  A fourfold display for 2 by 2 by \eqn{k} tables.
  Technical Report 217, York University, Psychology Department.
  \url{http://www.math.yorku.ca/SCS/Papers/4fold/4fold.ps.gz}
}
\seealso{
  \code{\link{mosaicplot}}
}
\examples{
data(UCBAdmissions)
## Use the Berkeley admission data as in Friendly (1995).
x <- aperm(UCBAdmissions, c(2, 1, 3))
dimnames(x)[[2]] <- c("Yes", "No")
names(dimnames(x)) <- c("Sex", "Admit?", "Department")
stats::ftable(x)

## Fourfold display of data aggregated over departments, with
## frequencies standardized to equate the margins for admission
## and sex.
## Figure 1 in Friendly (1994).
fourfoldplot(margin.table(x, c(1, 2)))

## Fourfold display of x, with frequencies in each table
## standardized to equate the margins for admission and sex.
## Figure 2 in Friendly (1994).
fourfoldplot(x)

## Fourfold display of x, with frequencies in each table
## standardized to equate the margins for admission. but not
## for sex.
## Figure 3 in Friendly (1994).
fourfoldplot(x, margin = 2)
}
\keyword{hplot}
\eof
\name{frame}
\title{Create / Start a New Plot Frame}
\usage{
plot.new()
frame()
}
\alias{plot.new}
\alias{frame}
\description{
  This function (\code{frame} is an alias for
  \code{plot.new}) causes the completion of plotting in the current plot
  (if there is one) and an advance to a new graphics frame.  This is
  used in all high-level plotting functions and also useful for skipping
  plots when a multi-figure region is in use.
}
\details{
  There is a hook called \code{"plot.new"} (see \code{\link{setHook}})
  called immediately after advancing the frame, which is used in the
  testing code to annotate the new page.  The hook function(s) are
  called with no argument.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole. (\code{frame}.)
}
\seealso{
  \code{\link{plot.window}}, \code{\link{plot.default}}.
}
\keyword{iplot}
\keyword{aplot}
\eof
\name{gray}
\alias{gray}
\alias{grey}
\title{Gray Level Specification}
\description{
  Create a vector of colors from a vector of gray levels.
}
\usage{
gray(level)
grey(level)
}
\arguments{
  \item{level}{a vector of desired gray levels between \code{0} and
    \code{1}; zero indicates \code{"black"} and one indicates
    \code{"white"}.}
}
\details{
  The values returned by \code{gray} can be used with a \code{col=}
  specification in graphics functions or in \code{\link{par}}.

  \code{grey} is an alias for \code{gray}.
}
\value{
  A vector of \dQuote{colors} of the same length as \code{level}.
}
\seealso{
  \code{\link{rainbow}},
  \code{\link{hsv}},
  \code{\link{rgb}}.
}
\examples{
gray(0:8 / 8)
}
\keyword{color}
\eof
\name{grid}
\alias{grid}
\title{Add Grid to a Plot}
\description{
  \code{grid} adds an \code{nx} by \code{ny} rectangular grid to an
  existing plot.
}
\usage{
grid(nx = NULL, ny = nx, col = "lightgray", lty = "dotted", lwd = NULL,
     equilogs = TRUE)
}
\arguments{
  \item{nx,ny}{number of cells of the grid in x and y direction.  When
    \code{NULL}, as per default, the grid aligns with the tick marks on
    the corresponding \emph{default} axis (i.e., tickmarks as computed by
    \code{\link{axTicks}}).  When \code{\link{NA}}, no grid lines are
    drawn in the corresponding direction.}
  \item{col}{character or (integer) numeric; color of the grid lines.}
  \item{lty}{character or (integer) numeric; line type of the grid lines.}
  \item{lwd}{non-negative numeric giving line width of the grid lines;
    defaults to \code{par("lwd")}.}
  \item{equilogs}{logical, only used when \emph{log} coordinates and
    alignment with the axis tick marks are active.  Setting{equilogs =
      FALSE} in that case gives \emph{non equidistant} tick aligned grid lines.}
}
\note{
  If more fine tuning is required, use \code{\link{abline}(h = ., v = .)}
  directly.
}
\seealso{
  \code{\link{plot}}, \code{\link{abline}}, \code{\link{lines}},
  \code{\link{points}}.
}
\examples{
plot(1:3)
grid(NA, 5, lwd = 2) # grid only in y-direction

data(iris)
## maybe change the desired number of tick marks:  par(lab=c(mx,my,7))
op <- par(mfcol = 1:2)
with(iris,
     {
     plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
          xlim = c(4, 8), ylim = c(2, 4.5), panel.first = grid(),
          main = "with(iris,  plot(...., panel.first = grid(), ..) )")
     plot(Sepal.Length, Sepal.Width, col = as.integer(Species),
          panel.first = grid(3, lty=1,lwd=2),
          main = "... panel.first = grid(3, lty=1,lwd=2), ..")
     }
    )
par(op)

}
\keyword{aplot}
\eof
\name{hist.POSIXt}
\alias{hist.POSIXt}
\alias{hist.Date}
\title{Histogram of a Date or Date-Time Object}
\description{
  Method for \code{\link{hist}} applied to date or date-time objects.
}
\usage{
\method{hist}{POSIXt}(x, breaks, \dots, plot = TRUE, freq = FALSE,
     start.on.monday = TRUE, format)

\method{hist}{Date}(x, breaks, \dots, plot = TRUE, freq = FALSE,
     start.on.monday = TRUE, format)
}
\synopsis{
hist.POSIXt(x, breaks, ..., xlab = deparse(substitute(x)),
            plot = TRUE, freq = FALSE,
            start.on.monday = TRUE, format)
hist.Date(x, breaks, ..., xlab = deparse(substitute(x)),
          plot = TRUE, freq = FALSE, start.on.monday = TRUE, format)
}
\arguments{
  \item{x}{an object inheriting from class \code{"POSIXt"} or \code{"Date"}.}
  \item{breaks}{
    a vector of cut points \emph{or} number giving the number of
    intervals which \code{x} is to be cut into \emph{or} an
    interval specification, one of \code{"days"}, \code{"weeks"},
    \code{"months"} or \code{"years"}, plus \code{"secs"}, \code{"mins"},
    \code{"hours"} for date-time objects.
 }
  \item{\dots}{graphical parameters, or arguments to
    \code{\link{hist.default}} such as \code{include.lowest},
      \code{right} and \code{labels}.}
  \item{plot}{logical.  If \code{TRUE} (default), a histogram is
    plotted, otherwise a list of breaks and counts is returned.}
  \item{freq}{logical; if \code{TRUE}, the
    histogram graphic is a representation of frequencies, i.e,
    the \code{counts} component of the result; if \code{FALSE},
    \emph{relative} frequencies (\dQuote{probabilities}) are plotted.}
  \item{start.on.monday}{logical. If \code{breaks = "weeks"}, should the
    week start on Mondays or Sundays?}
  \item{format}{for the x-axis labels. See \code{\link{strptime}}.}
}
\value{
  An object of class \code{"histogram"}: see \code{\link{hist}}.
}
\seealso{
  \code{\link{seq.POSIXt}}, \code{\link{axis.POSIXct}}, \code{\link{hist}}
}
\examples{
hist(.leap.seconds, "years", freq = TRUE)
hist(.leap.seconds,
     seq(ISOdate(1970, 1, 10), ISOdate(2002, 1, 1), "5 years"))

## 100 random dates in a 10-week period
random.dates <- as.Date("2001/1/1") + 70*runif(100)
hist(random.dates, "weeks", format = "\%d \%b")
}
\keyword{chron}
\keyword{dplot}
\keyword{hplot}
\eof
\name{hist}
\title{Histograms}
\usage{
hist(x, \dots)

\method{hist}{default}(x, breaks = "Sturges", freq = NULL, probability = !freq,
     include.lowest = TRUE, right = TRUE,
     density = NULL, angle = 45, col = NULL, border = NULL,
     main = paste("Histogram of" , xname),
     xlim = range(breaks), ylim = NULL,
     xlab = xname, ylab,
     axes = TRUE, plot = TRUE, labels = FALSE,
     nclass = NULL, \dots)
}
\alias{hist}
\alias{hist.default}
\arguments{
  \item{x}{a vector of values for which the histogram is desired.}
  \item{breaks}{one of:
    \itemize{
      \item a vector giving the breakpoints between histogram cells,
      \item a single number giving the number of cells for the histogram,
      \item a character string naming an algorithm to compute the
      number of cells (see Details),
      \item a function to compute the number of cells.
    }
    In the last three cases the number is a suggestion only.
  }
  \item{freq}{logical; if \code{TRUE}, the histogram graphic is a
    representation of frequencies, the \code{counts} component of
    the result; if \code{FALSE}, \emph{relative} frequencies
    (\dQuote{probabilities}), component \code{density},
    are plotted.   Defaults to \code{TRUE} \emph{iff} \code{breaks} are
    equidistant (and \code{probability} is not specified).}
  \item{probability}{an \emph{alias} for \code{!freq}, for S compatibility.}
  \item{include.lowest}{logical; if \code{TRUE}, an \code{x[i]} equal to
    the \code{breaks} value will be included in the first (or last, for
    \code{right = FALSE}) bar.  This will be ignored (with a warning)
    unless \code{breaks} is a vector.}
  \item{right}{logical; if \code{TRUE}, the histograms cells are
    right-closed (left open) intervals.}

  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise).}
  \item{col}{a colour to be used to fill the bars.
    The default of \code{NULL} yields unfilled bars.}
  \item{border}{the color of the border around the bars.  The default
    is to use the standard foreground color.}
  \item{main, xlab, ylab}{these arguments to \code{title} have useful
    defaults here.}
  \item{xlim, ylim}{the range of x and y values with sensible defaults.
    Note that \code{xlim} is \emph{not} used to define the histogram (breaks),
    but only for plotting (when \code{plot = TRUE}).}
  \item{axes}{logical.  If \code{TRUE} (default), axes are draw if the
    plot is drawn.}
  \item{plot}{logical.  If \code{TRUE} (default), a histogram is
    plotted, otherwise a list of breaks and counts is returned.}
  \item{labels}{logical or character.  Additionally draw labels on top
    of bars, if not \code{FALSE}; see \code{\link{plot.histogram}}.}
  \item{nclass}{numeric (integer).  For S(-PLUS) compatibility only,
    \code{nclass} is equivalent to \code{breaks} for a scalar or
    character argument.}
  \item{\dots}{further graphical parameters to \code{title} and \code{axis}.}
}
\description{
  The generic function \code{hist} computes a histogram of the given
  data values.  If \code{plot=TRUE}, the resulting object of
  \code{\link[base]{class} "histogram"} is plotted by
  \code{\link{plot.histogram}}, before it is returned.
}
\details{
  The definition of \dQuote{histogram} differs by source (with
  country-specific biases).  \R's default with equi-spaced breaks (also
  the default) is to plot the counts in the cells defined by
  \code{breaks}.  Thus the height of a rectangle is proportional to
  the number of points falling into the cell, as is the area
  \emph{provided} the breaks are equally-spaced.

  The default with non-equi-spaced breaks is to give
  a plot of area one, in which the \emph{area} of the rectangles is the
  fraction of the data points falling in the cells.

  If \code{right = TRUE} (default), the histogram cells are intervals
  of the form \code{(a, b]}, i.e., they include their right-hand endpoint,
  but not their left one, with the exception of the first cell when
  \code{include.lowest} is \code{TRUE}.

  For \code{right = FALSE}, the intervals are of the form \code{[a, b)},
  and \code{include.lowest} really has the meaning of
  \dQuote{\emph{include highest}}.

  A numerical tolerance of \eqn{10^{-7}}{1e-7} times the median bin size
  is applied when counting entries on the edges of bins.

  The default for \code{breaks} is \code{"Sturges"}: see
  \code{\link{nclass.Sturges}}.  Other names for which algorithms
  are supplied are \code{"Scott"} and \code{"FD"} /
  \code{"Friedman-Diaconis"} (with corresponding functions
  \code{\link{nclass.scott}} and \code{\link{nclass.FD}}).
  Case is ignored and partial matching is used.
  Alternatively, a function can be supplied which
  will compute the intended number of breaks as a function of \code{x}.
}
\value{
  an object of class \code{"histogram"} which is a list with components:
  \item{breaks}{the \eqn{n+1} cell boundaries (= \code{breaks} if that
  was a vector).}
  \item{counts}{\eqn{n} integers; for each cell, the number of
    \code{x[]} inside.}
  \item{density}{values \eqn{\hat f(x_i)}{f^(x[i])}, as estimated
    density values. If \code{all(diff(breaks) == 1)}, they are the
    relative frequencies \code{counts/n} and in general satisfy
    \eqn{\sum_i \hat f(x_i) (b_{i+1}-b_i) = 1}{sum[i; f^(x[i])
      (b[i+1]-b[i])] = 1}, where \eqn{b_i}{b[i]} = \code{breaks[i]}.}
  \item{intensities}{same as \code{density}. Deprecated, but retained
    for compatibility.}
  \item{mids}{the \eqn{n} cell midpoints.}
  \item{xname}{a character string with the actual \code{x} argument name.}
  \item{equidist}{logical, indicating if the distances between
    \code{breaks} are all the same.}
}
\note{
  The resulting value does \emph{not} depend on the values of
  the arguments \code{freq} (or \code{probability})
  or \code{plot}.  This is intentionally different from S.

  Prior to \R 1.7.0, the element \code{breaks} of the result was
  adjusted for numerical tolerances.  The nominal values are now
  returned even though tolerances are still used when counting.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Venables, W. N. and Ripley. B. D. (2002)
  \emph{Modern Applied Statistics with S}.  Springer.
}

\seealso{
  \code{\link{nclass.Sturges}}, \code{\link{stem}},
  \code{\link[stats]{density}},  \code{\link[MASS]{truehist}}.
}

\examples{
data(islands)
op <- par(mfrow=c(2, 2))
hist(islands)
utils::str(hist(islands, col="gray", labels = TRUE))

hist(sqrt(islands), br = 12, col="lightblue", border="pink")
##-- For non-equidistant breaks, counts should NOT be graphed unscaled:
r <- hist(sqrt(islands), br = c(4*0:5, 10*3:5, 70, 100, 140), col='blue1')
text(r$mids, r$density, r$counts, adj=c(.5, -.5), col='blue3')
sapply(r[2:3], sum)
sum(r$density * diff(r$breaks)) # == 1
lines(r, lty = 3, border = "purple") # -> lines.histogram(*)
par(op)

utils::str(hist(islands, br=12, plot= FALSE)) #-> 10 (~= 12) breaks
utils::str(hist(islands, br=c(12,20,36,80,200,1000,17000), plot = FALSE))

hist(islands, br=c(12,20,36,80,200,1000,17000), freq = TRUE,
     main = "WRONG histogram") # and warning
}
\keyword{dplot}
\keyword{hplot}
\keyword{distribution}
\eof
\name{hsv}
\alias{hsv}
\title{HSV Color Specification}
\description{
  Create a vector of colors from vectors specifying hue, saturation and
  value.
}
\usage{
hsv(h=1, s=1, v=1, gamma=1)
}
\arguments{
  \item{h,s,v}{numeric vectors of values in the range \code{[0,1]} for
    \dQuote{hue}, \dQuote{saturation} and \dQuote{value} to be combined
    to form a vector of colors.  Values in shorter arguments are
    recycled.}
  \item{gamma}{a \dQuote{gamma correction} exponent, \eqn{\gamma}}
}
\value{
  This function creates a vector of \dQuote{colors} corresponding to the
  given values in HSV space.  The values returned by \code{hsv} can be
  used with a \code{col=} specification in graphics functions or in
  \code{par}.
}
\section{Gamma correction}{
  For each color, \eqn{(r,g,b)} in RGB space (with all values in \eqn{[0,1]}),
  the final color corresponds to \eqn{(r^{\gamma}, g^{\gamma}, b^{\gamma})}.
}
\seealso{
  \code{\link{rainbow}},
  \code{\link{rgb}},
  \code{\link{gray}}.
}
\examples{
hsv(.5,.5,.5)

## Look at gamma effect:
n <- 20;  y <- -sin(3*pi*((1:n)-1/2)/n)
op <- par(mfrow=c(3,2),mar=rep(1.5,4))
for(gamma in c(.4, .6, .8, 1, 1.2, 1.5))
  plot(y, axes = FALSE, frame.plot = TRUE,
       xlab = "", ylab = "", pch = 21, cex = 30,
       bg = rainbow(n, start=.85, end=.1, gamma = gamma),
       main = paste("Red tones;  gamma=",format(gamma)))
par(op)
}
\keyword{color}
\keyword{dplot}
\eof
\name{identify}
\alias{identify}
\alias{identify.default}
\title{Identify Points in a Scatter Plot}
\usage{
identify(x, \dots)

\method{identify}{default}(x, y = NULL, labels = seq(along = x), pos = FALSE,
         n = length(x), plot = TRUE, offset = 0.5, \dots)
}
\arguments{
  \item{x,y}{coordinates of points in a scatter plot.  Alternatively, any
    object which defines coordinates (a plotting structure, time
    series etc.) can be given as \code{x} and \code{y} left undefined.}
  \item{labels}{an optional vector, the same length as \code{x} and
    \code{y}, giving labels for the points.}
  \item{pos}{if \code{pos} is \code{TRUE}, a component is added to the
    return value which indicates where text was plotted relative to each
    identified point (1=below, 2=left, 3=above and 4=right).}
  \item{n}{the maximum number of points to be identified.}
  \item{plot}{if \code{plot} is \code{TRUE}, the labels are printed at
    the points and if \code{FALSE} they are omitted.}
  \item{offset}{the distance (in character widths) which separates the
    label from identified points.}
  \item{\dots}{further arguments to \code{par(.)}.}
}
\description{
  \code{identify} reads the position of the graphics pointer when the
  (first) mouse button is pressed.  It then searches the coordinates
  given in \code{x} and \code{y} for the point closest to the pointer.
  If this point is close to the pointer, its index will be returned as
  part of the value of the call.
}
\details{
  \code{identify} is only supported on screen devices such as
  \code{X11}, \code{windows} and \code{quartz}.  On other devices the
  call will do nothing.
  
  If \code{plot} is \code{TRUE}, the point is labelled with
  the corresponding element of \code{text}.
  The labels are placed either below, to the left, above or to the right
  of the identified point, depending on where the cursor was.

#ifdef unix
  For the usual \code{\link{X11}} device the identification process is
  terminated by pressing any mouse button other than the first.
  For the \code{\link{quartz}} device the process is terminated by
  pressing the \code{ESC} key.
#endif
#ifdef windows
  The identification process is terminated by clicking the second button
  and selecting \sQuote{Stop} from the menu, or from the \sQuote{Stop}
  menu on the graphics window.
#endif
 
  On most devices which support \code{identify}, successful selection of
  a point is indicated by a bell sound unless
  \code{\link{options}(locatorBell=FALSE)} has been set.

  If the window is resized or hidden and then exposed before the identification
  process has terminated, any labels drawn by \code{identify}
  will disappear.  These will reappear once the identification process has 
  terminated and the window is resized or hidden and exposed again.
  This is because the labels drawn by \code{identify} are not
  recorded in the device's display list until the identification process has
  terminated.
}
\value{
  If \code{pos} is \code{FALSE}, an integer
  vector containing the indexes of the identified points.

  If \code{pos} is \code{TRUE}, a list containing a component
  \code{ind}, indicating which points were identified and a component
  \code{pos}, indicating where the labels were placed relative to the
  identified points.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{locator}}
}
\keyword{iplot}
\eof
\name{image}
\alias{image}
\alias{image.default}
\title{Display a Color Image}
\usage{
image(x, \dots)

\method{image}{default}(x, y, z, zlim, xlim, ylim, col = heat.colors(12),
      add = FALSE, xaxs = "i", yaxs = "i", xlab, ylab,
      breaks, oldstyle = FALSE, \dots)
}
\arguments{
  \item{x,y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in (strictly) ascending order.
    By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively. If the list has component \code{z} this
    is used for \code{z}.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{zlim}{the minimum and maximum \code{z} values for which colors
    should be plotted.  Each of the given colors will be used to color an
    equispaced interval of this range. The \emph{midpoints} of the
    intervals cover the range, so that values just outside the range
    will be plotted.}
  \item{xlim, ylim}{ranges for the plotted \code{x} and \code{y} values,
    defaulting to the range of the finite values of \code{x} and \code{y}.}
  \item{col}{a list of colors such as that generated by
    \code{\link{rainbow}}, \code{\link{heat.colors}},
    \code{\link{topo.colors}}, \code{\link{terrain.colors}} or similar
    functions.}
  \item{add}{logical; if \code{TRUE}, add to current plot (and disregard
    the following arguments).  This is rarely useful because
    \code{image} \dQuote{paints} over existing graphics.}
  \item{xaxs, yaxs}{style of x and y axis.  The default \code{"i"} is
    appropriate for images.  See \code{\link{par}}.}
  \item{xlab, ylab}{each a character string giving the labels for the x and
    y axis.  Default to the \sQuote{call names} of \code{x} or \code{y}, or to
    \code{""} if these where unspecified.}
  \item{breaks}{a set of breakpoints for the colours: must give one more
    breakpoint than colour.}
  \item{oldstyle}{logical. If true the midpoints of the colour intervals
    are equally spaced, and \code{zlim[1]} and \code{zlim[2]} were taken
    to be midpoints. (This was the default prior to \R 1.1.0.)
    The current default is to have colour intervals of equal lengths
    between the limits.}
  \item{\dots}{graphical parameters for \code{\link{plot}} may also be
    passed as arguments to this function, as can the plot aspect ratio
    \code{asp} (see \code{\link{plot.window}}).}
}
\description{
  Creates a grid of colored or gray-scale rectangles with colors
  corresponding to the values in \code{z}.  This can be used to display
  three-dimensional or spatial data aka \dQuote{images}.
  This is a generic function.

  The functions \code{\link{heat.colors}}, \code{\link{terrain.colors}}
  and \code{\link{topo.colors}} create heat-spectrum (red to white) and
  topographical color schemes suitable for displaying ordered data, with
  \code{n} giving the number of colors desired.
}
\details{
  The length of \code{x} should be equal to the \code{nrow(z)+1} or
  \code{nrow(z)}.  In the first case \code{x} specifies the boundaries
  between the cells: in the second case \code{x} specifies the midpoints
  of the cells.  Similar reasoning applies to \code{y}.  It probably
  only makes sense to specify the midpoints of an equally-spaced
  grid.  If you specify just one row or column and a length-one \code{x}
  or \code{y}, the whole user area in the corresponding direction is
  filled.

  If \code{breaks} is specified then \code{zlim} is unused and the
  algorithm used follows \code{\link{cut}}, so intervals are closed on
  the right and open on the left except for the lowest interval.
}
\note{
  Based on a function by Thomas Lumley
  \email{tlumley@u.washington.edu}.
}
\seealso{
  \code{\link{filled.contour}} or \code{\link[stats]{heatmap}} which can
  look nicer (but are less modular),
  \code{\link{contour}};

  \code{\link{heat.colors}}, \code{\link{topo.colors}},
  \code{\link{terrain.colors}}, \code{\link{rainbow}},
  \code{\link{hsv}}, \code{\link{par}}.
}
\examples{
x <- y <- seq(-4*pi, 4*pi, len=27)
r <- sqrt(outer(x^2, y^2, "+"))
image(z = z <- cos(r^2)*exp(-r/6), col=gray((0:32)/32))
image(z, axes = FALSE, main = "Math can be beautiful ...",
      xlab = expression(cos(r^2) * e^{-r/6}))
contour(z, add = TRUE, drawlabels = FALSE)

data(volcano)
x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = terrain.colors(100), axes = FALSE)
contour(x, y, volcano, levels = seq(90, 200, by=5), add = TRUE, col = "peru")
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
title(main = "Maunga Whau Volcano", font.main = 4)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{layout}
\alias{layout}
\alias{layout.show}
\alias{lcm}
\title{Specifying Complex Plot Arrangements}
\author{Paul R. Murrell}
\description{
  \code{layout} divides the device up into as many rows and columns as
  there are in matrix \code{mat}, with the column-widths and the
  row-heights specified in the respective arguments.
}
\usage{
layout(mat,
       widths = rep(1, dim(mat)[2]),
       heights= rep(1, dim(mat)[1]),
       respect= FALSE)

layout.show(n = 1)
lcm(x)
}
\arguments{
  \item{mat}{a matrix object specifying the location of the next
    \eqn{N} figures
    on the output device.  Each value in the matrix must be \code{0} or a
    positive integer.     If \eqn{N} is the largest positive integer in
    the matrix, then the integers \eqn{\{1,\dots,N-1\}} must also appear
    at least once in the matrix.}
  \item{widths}{a vector of values for the widths of columns on the
    device.  Relative widths are specified with numeric values.    Absolute
    widths (in centimetres) are specified with the \code{lcm()} function (see
    examples).}
  \item{heights}{a vector of values for the heights of rows on the device.
    Relative and absolute heights can be specified, see \code{widths} above.}
  \item{respect}{either a logical value or a matrix object.  If the
    latter, then it must have the same dimensions as \code{mat} and
    each value in the matrix must be either \code{0} or \code{1}.}
  \item{n}{number of figures to plot.}
  \item{x}{a dimension to be interpreted as a number of centimetres.}
}
\details{
    Figure \eqn{i} is allocated a region composed from a subset
    of these rows and columns, based on the rows and columns
    in which \eqn{i} occurs in \code{mat}.

    The \code{respect} argument controls whether a unit column-width is
    the same physical measurement on the device as a unit row-height.

    \code{layout.show(n)} plots (part of) the current layout, namely the
    outlines of the next \code{n} figures.

    \code{lcm} is a trivial function, to be used as \emph{the} interface
    for specifying absolute dimensions for the \code{widths} and
    \code{heights} arguments of \code{layout()}.
}
\value{
  \code{layout} returns the number of figures, \eqn{N}, see above.
}
\references{
  Murrell, P. R. (1999) Layouts: A mechanism for arranging plots on a page. 
  \emph{Journal of Computational and Graphical Statistics},
  \bold{8}, 121-134. 
  Chapter 5 of Paul Murrell's Ph.D. thesis.
}
\seealso{
  \code{\link{par}} with arguments \code{mfrow}, \code{mfcol}, or
  \code{mfg}.
}
\section{Warnings}{
  These functions are totally incompatible with the other mechanisms for
  arranging plots on a device: \code{\link{par}(mfrow)},
  \code{par(mfcol)} and \code{\link{split.screen}}.
}
\examples{
def.par <- par(no.readonly = TRUE) # save default, for resetting...

## divide the device into two rows and two columns
## allocate figure 1 all of row 1
## allocate figure 2 the intersection of column 2 and row 2
layout(matrix(c(1,1,0,2), 2, 2, byrow = TRUE))
## show the regions that have been allocated to each plot
layout.show(2)

## divide device into two rows and two columns
## allocate figure 1 and figure 2 as above
## respect relations between widths and heights
nf <- layout(matrix(c(1,1,0,2), 2, 2, byrow=TRUE), respect=TRUE)
layout.show(nf)

## create single figure which is 5cm square
nf <- layout(matrix(1), widths=lcm(5), heights=lcm(5))
layout.show(nf)


##-- Create a scatterplot with marginal histograms -----

x <- pmin(3, pmax(-3, rnorm(50)))
y <- pmin(3, pmax(-3, rnorm(50)))
xhist <- hist(x, breaks=seq(-3,3,0.5), plot=FALSE)
yhist <- hist(y, breaks=seq(-3,3,0.5), plot=FALSE)
top <- max(c(xhist$counts, yhist$counts))
xrange <- c(-3,3)
yrange <- c(-3,3)
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
layout.show(nf)

par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="")
par(mar=c(0,3,1,1))
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
par(mar=c(3,0,1,1))
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

par(def.par)#- reset to default
}
\keyword{iplot}
\keyword{dplot}
\keyword{environment}
\eof
\name{legend}
\alias{legend}
\title{Add Legends to Plots}
\usage{
legend(x, y = NULL, legend, fill = NULL, col = "black", lty, lwd, pch,
       angle = NULL, density = NULL, bty = "o", bg = par("bg"),
       pt.bg = NA, cex = 1, pt.cex = cex, xjust = 0, yjust = 1,
       x.intersp = 1, y.intersp = 1, adj = c(0, 0.5),
       text.width = NULL, text.col = par("col"),
       merge = do.lines && has.pch, trace = FALSE,
       plot = TRUE, ncol = 1, horiz = FALSE)
}
\description{
  This function can be used to add legends to plots.  Note that a call
  to the function \code{\link{locator}} can be used in place of the \code{x}
  and \code{y} arguments.
}
\arguments{
  \item{x, y}{the x and y co-ordinates to be used to position the legend.
    They can be specified in any way which is accepted by
    \code{\link{xy.coords}}: See Details.}
  \item{legend}{a vector of text values or an \code{\link{expression}}
    of length \eqn{\ge 1}{>= 1}, or a \code{\link{call}} (as resulting
    from \code{\link{substitute}}) to appear in the legend.}
  \item{fill}{if specified, this argument will cause boxes filled
    with the specified colors (or shaded in the specified colors)
    to appear beside the legend text.}
  \item{col}{the color of points or lines appearing in the legend.}
  \item{lty,lwd}{the line types and widths for lines appearing in the
    legend.  One of these two \emph{must} be specified for line drawing.}
  \item{pch}{the plotting symbols appearing in the legend, either as
    vector of 1-character strings, or one (multi character)
    string. \emph{Must} be specified for symbol drawing.}
  \item{angle}{angle of shading lines.}
  \item{density}{the density of shading lines, if numeric and
    positive. If \code{NULL} or negative or \code{NA} color filling
    is assumed.}
  \item{bty}{the type of box to be drawn around the legend.  The allowed
    values are \code{"o"} (the default) and \code{"n"}.}
  \item{bg}{the background color for the legend box.  (Note that this is
    only used if \code{bty != "n"}.)}
  \item{pt.bg}{the background color for the \code{\link{points}}.}
  \item{cex}{character expansion factor \bold{relative} to current
    \code{par("cex")}.}
  \item{pt.cex}{expansion factor(s) for the points.}
  \item{xjust}{how the legend is to be justified relative to the legend
    x location.  A value of 0 means left justified, 0.5 means centered
    and 1 means right justified.}
  \item{yjust}{the same as \code{xjust} for the legend y location.}
  \item{x.intersp}{character interspacing factor for horizontal (x) spacing.}
  \item{y.intersp}{the same for vertical (y) line distances.}
  \item{adj}{numeric of length 1 or 2; the string adjustment for legend
      text.  Useful for y-adjustment when \code{labels} are
      \link{plotmath} expressions.}
  \item{text.width}{the width of the legend text in x (\code{"user"})
    coordinates.
    Defaults to the proper value computed by \code{\link{strwidth}(legend)}.}
  \item{text.col}{the color used for the legend text.}
  \item{merge}{logical; if \code{TRUE}, \dQuote{merge} points and lines but
    not filled boxes.  Defaults to \code{TRUE} if there are points and lines.}
  \item{trace}{logical; if \code{TRUE}, shows how \code{legend} does all
    its magical computations.}
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted but the
    sizes are returned.}
  \item{ncol}{the number of columns in which to set the legend items
    (default is 1, a vertical legend).}
  \item{horiz}{logical; if \code{TRUE}, set the legend horizontally rather than
     vertically (specifying \code{horiz} overrides the \code{ncol}
     specification).}
}
\details{
  Arguments \code{x, y, legend} are interpreted in a non-standard way to
  allow the coordinates to be specified \emph{via} one or two arguments.
  If \code{legend} is missing and \code{y} is not numeric, it is assumed
  that the second argument is intended to be \code{legend} and that the
  first argument specifies the coordinates.

  The coordinates can be specified in any way which is accepted by
  \code{\link{xy.coords}}.  If this gives the coordinates of one point,
  it is used as the top-left coordinate of the rectangle containing the
  legend.  If it gives the coordinates of two points, these specify
  opposite corners of the rectangle (either pair of corners, in any
  order).

  \dQuote{Attribute} arguments such as \code{col}, \code{pch}, \code{lty},
  etc, are recycled if necessary.  \code{merge} is not.

  Points are drawn \emph{after} lines in order that they can cover the
  line with their background color \code{pt.bg}, if applicable.

  See the examples for how to right-justify labels.
}
\value{
  A list with list components
  \item{rect}{a list with components
    \describe{
      \item{\code{w, h}}{positive numbers giving \bold{w}idth and
	\bold{h}eight of the legend's box.}
      \item{\code{left, top}}{x and y coordinates of upper left corner
	of the box.}
    }
  }
  \item{text}{a list with components
    \describe{
      \item{\code{x, y}}{numeric vectors of length \code{length(legend)},
	giving the x and y coordinates of the legend's text(s).}
    }
  }
  returned invisibly.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{barplot}} which uses \code{legend()}, and
  \code{\link{text}} for more examples of math expressions.
}
\examples{
## Run the example in '?matplot' or the following:
leg.txt <- c("Setosa     Petals", "Setosa     Sepals",
             "Versicolor Petals", "Versicolor Sepals")
y.leg <- c(4.5, 3, 2.1, 1.4, .7)
cexv  <- c(1.2, 1, 4/5, 2/3, 1/2)
matplot(c(1,8), c(0,4.5), type = "n", xlab = "Length", ylab = "Width",
        main = "Petal and Sepal Dimensions in Iris Blossoms")
for (i in seq(cexv)) {
  text  (1, y.leg[i]-.1, paste("cex=",formatC(cexv[i])), cex=.8, adj = 0)
  legend(3, y.leg[i], leg.txt, pch = "sSvV", col = c(1, 3), cex = cexv[i])
}

## 'merge = TRUE' for merging lines & points:
x <- seq(-pi, pi, len = 65)
plot(x, sin(x), type = "l", ylim = c(-1.2, 1.8), col = 3, lty = 2)
points(x, cos(x), pch = 3, col = 4)
lines(x, tan(x), type = "b", lty = 1, pch = 4, col = 6)
title("legend(..., lty = c(2, -1, 1), pch = c(-1,3,4), merge = TRUE)",
      cex.main = 1.1)
legend(-1, 1.9, c("sin", "cos", "tan"), col = c(3,4,6), text.col= "green4",
       lty = c(2, -1, 1), pch = c(-1, 3, 4), merge = TRUE, bg='gray90')

## right-justifying a set of labels: thanks to Uwe Ligges
x <- 1:5; y1 <- 1/x; y2 <- 2/x
plot(rep(x, 2), c(y1, y2), type="n", xlab="x", ylab="y")
lines(x, y1); lines(x, y2, lty=2)
temp <- legend(5, 2, legend = c(" ", " "),
               text.width = strwidth("1,000,000"),
               lty = 1:2, xjust = 1, yjust = 1)
text(temp$rect$left + temp$rect$w, temp$text$y,
     c("1,000", "1,000,000"), pos=2)


##--- log scaled Examples ------------------------------
leg.txt <- c("a one", "a two")

par(mfrow = c(2,2))
for(ll in c("","x","y","xy")) {
  plot(2:10, log=ll, main=paste("log = '",ll,"'", sep=""))
  abline(1,1)
  lines(2:3,3:4, col=2) #
  points(2,2, col=3)    #
  rect(2,3,3,2, col=4)
  text(c(3,3),2:3, c("rect(2,3,3,2, col=4)",
                     "text(c(3,3),2:3,\"c(rect(...)\")"), adj = c(0,.3))
  legend(list(x=2,y=8), legend = leg.txt, col=2:3, pch=1:2,
         lty=1, merge=TRUE)#, trace=TRUE)
}
par(mfrow=c(1,1))

##-- Math expressions:  ------------------------------
x <- seq(-pi, pi, len = 65)
plot(x, sin(x), type="l", col = 2,xlab=expression(phi),ylab=expression(f(phi)))
abline(h=-1:1, v=pi/2*(-6:6), col="gray90")
lines(x, cos(x), col = 3, lty = 2)
ex.cs1 <- expression(plain(sin) * phi,  paste("cos", phi))# 2 ways
utils::str(legend(-3, .9, ex.cs1, lty=1:2, plot=FALSE, adj = c(0, .6)))# adj y !
legend(-3, .9, ex.cs1, lty=1:2, col=2:3,    adj = c(0, .6))

x <- rexp(100, rate = .5)
hist(x, main = "Mean and Median of a Skewed Distribution")
abline(v = mean(x),   col=2, lty=2, lwd=2)
abline(v = median(x), col=3, lty=3, lwd=2)
ex12 <- expression(bar(x) == sum(over(x[i], n), i==1, n),
                   hat(x) == median(x[i], i==1,n))
utils::str(legend(4.1, 30, ex12, col = 2:3, lty=2:3, lwd=2))

## 'Filled' boxes -- for more, see example(plotfactor)
op <- par(bg="white") # to get an opaque box for the legend
data(PlantGrowth)
plot(cut(weight, 3) ~ group, data = PlantGrowth, col = NULL,
     density = 16*(1:3))
par(op)

## Using 'ncol' :
x <- 0:64/64
matplot(x, outer(x, 1:7, function(x, k) sin(k * pi * x)),
        type = "o", col = 1:7, ylim = c(-1, 1.5), pch = "*")
op <- par(bg="antiquewhite1")
legend(0, 1.5, paste("sin(",1:7,"pi * x)"), col=1:7, lty=1:7, pch = "*",
       ncol = 4, cex=.8)
legend(.8,1.2, paste("sin(",1:7,"pi * x)"), col=1:7, lty=1:7, pch = "*",cex=.8)
legend(0, -.1, paste("sin(",1:4,"pi * x)"), col=1:4, lty=1:4, ncol=2, cex=.8)
legend(0, -.4, paste("sin(",5:7,"pi * x)"), col=5:7,  pch=24, ncol=2, cex=1.5,
       pt.bg= "pink", pt.cex= 1:3)
par(op)

## point covering line :
y <- sin(3*pi*x)
plot(x, y, type="l", col="blue", main = "points with bg & legend(*, pt.bg)")
points(x, y, pch=21, bg="white")
legend(.4,1, "sin(c x)", pch=21, pt.bg="white", lty=1, col = "blue")
}
\keyword{aplot}
\eof
\name{lines}
\alias{lines}
\alias{lines.default}
\title{Add Connected Line Segments to a Plot}
\description{
  A generic function taking coordinates given in various ways and
  joining the corresponding points with line segments.
}
\usage{
lines(x, \dots)

\method{lines}{default}(x, y = NULL, type = "l", col = par("col"),
      lty = par("lty"), \dots)
}
\arguments{
  \item{x, y}{coordinate vectors of points to join.}
  \item{type}{character indicating the type of plotting; actually any of
    the \code{type}s as in \code{\link{plot}}.}
  \item{col}{color to use. This can be vector of length greater than
    one, but only the first value will be used.}
  \item{lty}{line type to use.}
  \item{\dots}{Further graphical parameters (see \code{\link{par}}) may
    also be supplied as arguments, particularly, line type, \code{lty} and
    line width, \code{lwd}.}
}
\details{
  The coordinates can be passed to \code{lines} in a plotting structure
  (a list with \code{x} and \code{y} components), a time series,
  etc. See \code{\link{xy.coords}}.

  The coordinates can contain \code{NA} values. If a point contains
  \code{NA} in either its \code{x} or \code{y} value, it is omitted from
  the plot, and lines are not drawn to or from such points.  Thus
  missing values can be used to achieve breaks in lines.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{points}},
  \code{\link{plot}},
  and the underlying \dQuote{primitive} \code{\link{plot.xy}}.

  \code{\link{par}} for how to specify colors.
}
\examples{
data(cars)
# draw a smooth line through a scatter plot
plot(cars, main="Stopping Distance versus Speed")
lines(lowess(cars))
}
\keyword{aplot}
\eof
\name{locator}
\alias{locator}
\title{Graphical Input}
\description{
  Reads the position of the graphics cursor when the (first) mouse
  button is pressed.
}
\usage{
locator(n = 512, type = "n", \dots)
}
\arguments{
  \item{n}{the maximum number of points to locate.  Valid values start
    at 1.}
  \item{type}{One of \code{"n"}, \code{"p"}, \code{"l"} or
    \code{"o"}. If \code{"p"} or \code{"o"} the points are
    plotted; if \code{"l"}  or \code{"o"} they are joined by lines.}
  \item{\dots}{additional graphics parameters used if \code{type != "n"}
    for plotting the locations.}
}
\value{
  A list containing \code{x} and \code{y} components which are the
  coordinates of the identified points in the user coordinate system,
  i.e., the one specified by \code{\link{par}("usr")}.
}
\details{
  \code{locator} is only supported on screen devices such as
  \code{X11}, \code{windows} and \code{quartz}.  On other devices the
  call will do nothing.
  
  Unless the process is terminated prematurely by the user (see below)
  at most \code{n} positions are determined.

#ifdef unix
  For the usual \code{\link{X11}} device the identification process is
  terminated by pressing any mouse button other than the first.
  For the \code{\link{quartz}} device the process is terminated by
  pressing the \code{ESC} key.
#endif
#ifdef windows
  The identification process can be terminated by clicking the second
  button and selecting \sQuote{Stop} from the menu, or from the
  \sQuote{Stop} menu on the graphics window.
#endif

  The current graphics parameters apply just as if \code{plot.default}
  has been called with the same value of \code{type}. The plotting of
  the points and lines is subject to clipping, but locations outside the
  current clipping rectangle will be returned.

  On most devices which support \code{locator}, successful selection of
  a point is indicated by a bell sound unless
  \code{\link{options}(locatorBell=FALSE)} has been set.

  If the window is resized or hidden and then exposed before the input
  process has terminated, any lines or points drawn by \code{locator}
  will disappear.  These will reappear once the input process has
  terminated and the window is resized or hidden and exposed again.
  This is because the points and lines drawn by \code{locator} are not
  recorded in the device's display list until the input process has
  terminated.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{identify}}
}
\keyword{iplot}
\eof
\name{matplot}
\alias{matplot}
\alias{matpoints}
\alias{matlines}
\title{Plot Columns of Matrices}
\usage{
matplot(x, y, type = "p", lty = 1:5, lwd = 1, pch = NULL, col = 1:6,
        cex = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
        \dots, add = FALSE, verbose = getOption("verbose"))
matpoints(x, y, type = "p", lty = 1:5, lwd = 1, pch = NULL, col = 1:6, \dots)
matlines (x, y, type = "l", lty = 1:5, lwd = 1, pch = NULL, col = 1:6, \dots)
}
\arguments{
  \item{x,y}{vectors or matrices of data for plotting.  The number of
    rows should match.  If one of them are missing, the other is taken
    as \code{y} and an \code{x} vector of \code{1:n} is used.
    Missing values (\code{NA}s) are allowed.}
  \item{type}{character string (length 1 vector) or vector of 1-character
    strings indicating the type of plot for each
    column of \code{y}, see \code{\link{plot}} for all possible
    \code{type}s.  The first character of \code{type}
    defines the first plot, the second character the second, etc.
    Characters in \code{type} are cycled through; e.g., \code{"pl"}
    alternately plots points and lines.}
  \item{lty,lwd}{vector of line types and widths.
    The first element is for the first column, the second element for
    the second column, etc., even if lines are not plotted for all
    columns. Line types will be used cyclically until all plots are
    drawn.}
  \item{pch}{character string or vector of 1-characters or integers for
    plotting characters, see \code{\link{points}}.
    The first character is the plotting-character for the first plot,
    the second for the second, etc.  The default is the digits (1
    through 9, 0) then the letters.
%%__FIXME__ Which of the following is still true; what's the "right" UI ?
%  To mix special plotting symbols (those specified by integers) and
%  plotting characters, either use character escapes \code{pch="Xe002"}
%  or figure out the numeric equivalent of the ASCII character,
%  \code{pch=c(88,2)}.
  }
  \item{col}{vector of colors.  Colors are used cyclically.}
  \item{cex}{vector of character expansion sizes, used cyclically.}
  \item{xlab, ylab}{titles for x and y axes, as in \code{\link{plot}}.}
  \item{xlim, ylim}{ranges of x and y axes, as in \code{\link{plot}}.}
  \item{\dots}{Graphical parameters (see \code{\link{par}}) and any further
    arguments of \code{plot}, typically \code{\link{plot.default}}, may also be
    supplied as arguments to this function.  Hence, the high-level
    graphics control arguments described under \code{\link{par}} and the
    arguments to \code{\link{title}} may be supplied to this function.}
  \item{add}{logical.  If \code{TRUE}, plots are added to current one,
    using \code{\link{points}} and \code{\link{lines}}.}
  \item{verbose}{logical.  If \code{TRUE}, write one line of what is
    done.}
}
\section{Side Effects}{Function \code{matplot} generates a new plot;
  \code{matpoints} and \code{matlines} add to the current one.}
\description{
  Plot the columns of one matrix against the columns of another.
}
\details{
  Points involving missing values are not plotted.

  The first column of \code{x} is plotted against the first column of
  \code{y}, the second column of \code{x} against the second column of
  \code{y}, etc.  If one matrix has fewer columns, plotting will cycle
  back through the columns again.  (In particular, either \code{x} or
  \code{y} may be a vector, against which all columns of the other
  argument will be plotted.)

  The first element of \code{col, cex, lty, lwd} is used to plot the axes
  as well as the first line.

  Because plotting symbols are drawn with lines and because these
  functions may be changing the line style, you should probably specify
  \code{lty=1} when using plotting symbols.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{points}}, \code{\link{lines}},
  \code{\link{matrix}}, \code{\link{par}}.
}
\examples{
matplot((-4:5)^2, main = "Quadratic") # almost identical to plot(*)
sines <- outer(1:20, 1:4, function(x, y) sin(x / 20 * pi * y))
matplot(sines, pch = 1:4, type = "o", col = rainbow(ncol(sines)))

x <- 0:50/50
matplot(x, outer(x, 1:8, function(x, k) sin(k*pi * x)),
        ylim = c(-2,2), type = "plobcsSh",
        main= "matplot(,type = \"plobcsSh\" )")
## pch & type =  vector of 1-chars :
matplot(x, outer(x, 1:4, function(x, k) sin(k*pi * x)),
        pch = letters[1:4], type = c("b","p","o"))

data(iris)                  # is data.frame with 'Species' factor
table(iris$Species)
iS <- iris$Species == "setosa"
iV <- iris$Species == "versicolor"
op <- par(bg = "bisque")
matplot(c(1, 8), c(0, 4.5), type= "n", xlab = "Length", ylab = "Width",
        main = "Petal and Sepal Dimensions in Iris Blossoms")
matpoints(iris[iS,c(1,3)], iris[iS,c(2,4)], pch = "sS", col = c(2,4))
matpoints(iris[iV,c(1,3)], iris[iV,c(2,4)], pch = "vV", col = c(2,4))
legend(1, 4, c("    Setosa Petals", "    Setosa Sepals",
               "Versicolor Petals", "Versicolor Sepals"),
       pch = "sSvV", col = rep(c(2,4), 2))

nam.var <- colnames(iris)[-5]
nam.spec <- as.character(iris[1+50*0:2, "Species"])
iris.S <- array(NA, dim = c(50,4,3), dimnames = list(NULL, nam.var, nam.spec))
for(i in 1:3) iris.S[,,i] <- data.matrix(iris[1:50+50*(i-1), -5])

matplot(iris.S[,"Petal.Length",], iris.S[,"Petal.Width",], pch="SCV",
        col = rainbow(3, start = .8, end = .1),
        sub = paste(c("S", "C", "V"), dimnames(iris.S)[[3]],
                    sep = "=", collapse= ",  "),
        main = "Fisher's Iris Data")
par(op)
}
\keyword{hplot}
\keyword{aplot}
\keyword{array}
\eof
\name{mosaicplot}
\alias{mosaicplot}
\alias{mosaicplot.default}
\alias{mosaicplot.formula}
\title{Mosaic Plots}
\description{Plots a mosaic on the current graphics device.}
\usage{
mosaicplot(x, \dots)

\method{mosaicplot}{default}(x, main = deparse(substitute(x)), 
                   sub = NULL, xlab = NULL, ylab = NULL,
                   sort = NULL, off = NULL, dir = NULL,
                   color = FALSE, shade = FALSE, margin = NULL,
                   cex.axis = 0.66, las = par("las"),
                   type = c("pearson", "deviance", "FT"), \dots)

\method{mosaicplot}{formula}(formula, data = NULL, \dots,
          main = deparse(substitute(data)), subset)
}
\arguments{
  \item{x}{a contingency table in array form, with optional category
    labels specified in the \code{dimnames(x)} attribute.  The table is
    best created by the \code{table()} command.}
  \item{main}{character string for the mosaic title.}
  \item{sub}{character string for the mosaic sub-title (at bottom).}
  \item{xlab,ylab}{x- and y-axis labels used for the plot; by default,
    the first and second element of \code{names(dimnames(X))} (i.e., the
    name of the first and second variable in \code{X}).}
  \item{sort}{vector ordering of the variables, containing a permutation
    of the integers \code{1:length(dim(x))} (the default).}
  \item{off}{vector of offsets to determine percentage spacing at each
    level of the mosaic (appropriate values are between 0 and 20,
    and the default is 10 at each level).  There should be one
    offset for each dimension of the contingency table.}
  \item{dir}{vector of split directions (\code{"v"} for vertical and
    \code{"h"} for horizontal) for each level of the mosaic, one
    direction for each dimension of the contingency table.  The
    default consists of alternating directions, beginning with a
    vertical split.}
  \item{color}{logical or (recycling) vector of colors for color
    shading, used only when \code{shade} is \code{FALSE}.  The default
    \code{color=FALSE} gives empty boxes with no shading.}
  \item{shade}{a logical indicating whether to produce extended mosaic
    plots, or a numeric vector of at most 5 distinct positive numbers
    giving the absolute values of the cut points for the residuals.  By
    default, \code{shade} is \code{FALSE}, and simple mosaics are
    created.  Using \code{shade = TRUE} cuts absolute values at 2 and
    4.}
  \item{margin}{a list of vectors with the marginal totals to be fit in
    the log-linear model.  By default, an independence model is fitted.
    See \code{\link[stats]{loglin}} for further information.}
  \item{cex.axis}{The magnification to be used for axis annotation,
    as a multiple of \code{par("cex")}.}
  \item{las}{numeric; the style of axis labels, see \code{\link{par}}.}
  \item{type}{a character string indicating the type of residual to be
    represented.  Must be one of \code{"pearson"} (giving components of
    Pearson's \eqn{\chi^2}{chi-squared}), \code{"deviance"} (giving
    components of the likelihood ratio \eqn{\chi^2}{chi-squared}), or
    \code{"FT"} for the Freeman-Tukey residuals.  The value of this
    argument can be abbreviated.}
  \item{formula}{a formula, such as \code{y ~ x}.}
  \item{data}{a data frame (or list), or a contingency table from which
    the variables in \code{formula} should be taken.}
  \item{\dots}{further arguments to be passed to or from methods.}
  \item{subset}{an optional vector specifying a subset of observations
    in the data frame to be used for plotting.}
}
\details{
  This is a generic function.  It currently has a default method
  (\code{\link{mosaicplot.default}}) and a formula interface
  (\code{\link{mosaicplot.formula}}).

  Extended mosaic displays show the standardized residuals of a
  loglinear model of the counts from by the color and outline of the
  mosaic's tiles.  (Standardized residuals are often referred to a
  standard normal distribution.)  Negative residuals are drawn in shaded
  of red and with broken outlines; positive ones are drawn in blue with
  solid outlines.

  For the formula method, if \code{data} is an object inheriting from
  classes \code{"table"} or \code{"ftable"}, or an array with more than
  2 dimensions, it is taken as a contingency table, and hence all
  entries should be nonnegative.  In this case, the left-hand side of
  \code{formula} should be empty, and the variables on the right-hand
  side should be taken from the names of the dimnames attribute of the
  contingency table.  A marginal table of these variables is computed,
  and a mosaic of this table is produced.

  Otherwise, \code{data} should be a data frame or matrix, list or
  environment containing the variables to be cross-tabulated.  In this
  case, after possibly selecting a subset of the data as specified by
  the \code{subset} argument, a contingency table is computed from the
  variables given in \code{formula}, and a mosaic is produced from
  this.

  See Emerson (1998) for more information and a case study with
  television viewer data from Nielsen Media Research.

  Missing values are not supported unless \code{data} contains variables
  to be cross-tabulated, when rows containing missing values are omitted.
}
\author{
  S-PLUS original by John Emerson \email{emerson@stat.yale.edu}.
  Originally modified and enhanced for \R by KH.
}
\references{
  Hartigan, J.A., and Kleiner, B. (1984)
  A mosaic of television ratings. \emph{The American Statistician},
  \bold{38}, 32--35.

  Emerson, J. W. (1998)
  Mosaic displays in S-PLUS: a general implementation and a case study.
  \emph{Statistical Computing and Graphics Newsletter (ASA)},
  \bold{9}, 1, 17--23.

  Friendly, M. (1994)
  Mosaic displays for multi-way contingency tables.
  \emph{Journal of the American Statistical Association}, \bold{89},
  190--200.

  The home page of Michael Friendly
  (\url{http://www.math.yorku.ca/SCS/friendly.html}) provides
  information on various aspects of graphical methods for analyzing
  categorical data, including mosaic plots.
}
\seealso{
  \code{\link{assocplot}},
  \code{\link[stats]{loglin}}.
}
\examples{
data(Titanic)
mosaicplot(Titanic, main = "Survival on the Titanic", color = TRUE)
## Formula interface for tabulated data:
mosaicplot(~ Sex + Age + Survived, data = Titanic, color = TRUE)

data(HairEyeColor)
mosaicplot(HairEyeColor, shade = TRUE)
## Independence model of hair and eye color and sex.  Indicates that
## there are significantly more blue eyed blonde females than expected
## in the case of independence (and too few brown eyed blonde females).

mosaicplot(HairEyeColor, shade = TRUE, margin = list(c(1,2), 3))
## Model of joint independence of sex from hair and eye color.  Males
## are underrepresented among people with brown hair and eyes, and are
## overrepresented among people with brown hair and blue eyes, but not
## "significantly".

## Formula interface for raw data: visualize crosstabulation of numbers
## of gears and carburettors in Motor Trend car data.
data(mtcars)
mosaicplot(~ gear + carb, data = mtcars, color = TRUE, las = 1)
mosaicplot(~ gear + carb, data = mtcars, color = 2:3, las = 1)# color recycling
}
\keyword{hplot}
\eof
\name{mtext}
\title{Write Text into the Margins of a Plot}
\usage{
mtext(text, side = 3, line = 0, outer = FALSE, at = NA,
      adj = NA, cex = NA, col = NA, font = NA, vfont = NULL, \dots)
}
\alias{mtext}
\arguments{
  \item{text}{one or more character strings or expressions.}
  \item{side}{on which side of the plot (1=bottom, 2=left, 3=top, 4=right).}
  \item{line}{on which MARgin line, starting at 0 counting outwards.}
  \item{outer}{use outer margins if available.}
  \item{at}{give location in user-coordinates.  If \code{length(at)==0}
    (the default), the location will be determined by \code{adj}.
  }
  \item{adj}{adjustment for each string. For strings parallel
    to the axes, \code{adj=0} means left or bottom alignment, and
    \code{adj=1} means right or top alignment.
    If \code{adj} is not a finite value (the default), the value of
    \code{par("las")} determines the adjustment.  For strings plotted
    parallel to the axis the default is to centre the string.}
  \item{\dots}{Further graphical parameters (see \code{\link{text}} and
    \code{\link{par}}) ; currently supported are:}
  \item{cex}{character expansion factor (default = 1).}
  \item{col}{color to use.}
  \item{font}{font for text.}
  \item{vfont}{vector font for text.}
}
% mtext is defined via do_mtext(.) in  src/main/plot.c ---
\description{
  Text is written in one of the four margins of the current figure region
  or one of the outer margins of the device region.
}
\details{
  The \dQuote{user coordinates} in the outer margins always range from zero to
  one, and are not affected by the user coordinates in the figure
  region(s) --- \R is differing here from other implementations of S.

  The arguments \code{side}, \code{line}, \code{at}, \code{at},
  \code{adj}, the further graphical parameters and even \code{outer} can
  be vectors, and recycling will take place to plot as many strings as
  the longest of the vector arguments.  Note that a vector \code{adj}
  has a different meaning from \code{\link{text}}.

  \code{adj = 0.5} will centre the string, but for \code{outer=TRUE} on
  the device region rather than the plot region.

  Parameter \code{las} will determine the orientation of the string(s).
  For strings plotted perpendicular to the axis the default justification
  is to place the end of the string nearest the axis on the specified
  line.  (Note that this differs from S, which uses \code{srt} if
  \code{at} is supplied and \code{las} if it is not.)

  Note that if the text is to be plotted perpendicular to the axis,
  \code{adj} determines the justification of the string \emph{and} the
  position along the axis unless \code{at} is specified.
}
\section{Side Effects}{The given text is written onto the current plot.}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{title}}, \code{\link{text}}, \code{\link{plot}},
  \code{\link{par}};
  \code{\link{plotmath}} for details on mathematical annotation.
}
\examples{
plot(1:10, (-4:5)^2, main="Parabola Points", xlab="xlab")
mtext("10 of them")
for(s in 1:4)
    mtext(paste("mtext(..., line= -1, {side, col, font} = ",s,
          ", cex = ", (1+s)/2, ")"), line = -1,
          side=s, col=s, font=s, cex= (1+s)/2)
mtext("mtext(..., line= -2)", line = -2)
mtext("mtext(..., line= -2, adj = 0)", line = -2, adj =0)
##--- log axis :
plot(1:10, exp(1:10), log='y', main="log='y'", xlab="xlab")
for(s in 1:4) mtext(paste("mtext(...,side=",s,")"), side=s)
}
\keyword{aplot}


\eof
\name{n2mfrow}
\alias{n2mfrow}
\title{Compute Default mfrow From Number of Plots}
\description{
  Easy setup for plotting multiple figures (in a rectangular layout) on
  one page.  This computes a sensible default for
  \code{\link{par}(mfrow)}.
}
\usage{
n2mfrow(nr.plots)
}
\arguments{
  \item{nr.plots}{integer; the number of plot figures you'll want to draw.}
}
\value{
  A length two integer vector \code{nr, nc} giving the number of rows
  and columns, fulfilling \code{nr >= nc >= 1} and \code{nr * nc >= nr.plots}.
}
\author{Martin Maechler}
\seealso{\code{\link{par}}, \code{\link{layout}}.}
\examples{
n2mfrow(8) # 3 x 3

n <- 5 ; x <- seq(-2,2, len=51)
## suppose now that 'n' is not known {inside function}
op <- par(mfrow = n2mfrow(n))
for (j in 1:n)
   plot(x, x^j, main = substitute(x^ exp, list(exp = j)), type='l', col="blue")

sapply(1:10, n2mfrow)
}
\keyword{dplot}
\keyword{utilities}
\eof
\name{nclass}
\alias{nclass.Sturges}
\alias{nclass.scott}
\alias{nclass.FD}
\title{
Compute the Number of Classes for a Histogram
}
\description{
  Compute the number of classes for a histogram, for use internally in
  \code{\link{hist}}.
}
\usage{
nclass.Sturges(x)
nclass.scott(x)
nclass.FD(x)
}
\arguments{
  \item{x}{
    A data vector.
  }
}
\value{
  The suggested number of classes.
}
\details{
  \code{nclass.Sturges} uses Sturges' formula, implicitly basing bin
  sizes on the range of the data.
  
  \code{nclass.scott} uses Scott's choice for a normal distribution based on
  the estimate of the standard error.

  \code{nclass.FD} uses the
  Freedman-Diaconis choice based on the inter-quartile range.
}
\references{
  Venables, W. N. and Ripley, B. D. (2002)
  \emph{Modern Applied Statistics with S-PLUS.}
  Springer, page 112.

  Freedman, D. and Diaconis, P. (1981)
  On the histogram as a density estimator: \eqn{L_2} theory.
  \emph{Zeitschrift für Wahrscheinlichkeitstheorie und verwandte
    Gebiete} \bold{57}, 453--476.

  Scott, D. W. (1979) On optimal and data-based histograms.
  \emph{Biometrika} \bold{66}, 605--610.

  Scott, D. W. (1992)
  \emph{Multivariate Density Estimation. Theory, Practice, and
    Visualization}. Wiley.
}
\seealso{
  \code{\link{hist}}
}
\keyword{univar}
\eof
\name{pairs}
\alias{pairs}
\alias{pairs.default}
\alias{pairs.formula}

\title{Scatterplot Matrices}
\description{
  A matrix of scatterplots is produced.
}
\synopsis{
pairs(x, \dots)
pairs.formula(formula, data = NULL, \dots, subset)
pairs.default(x, labels, panel = points, \dots,
              main = NULL, oma = NULL,
              font.main = par("font.main"), cex.main = par("cex.main"),
              lower.panel = panel, upper.panel = panel,
              diag.panel = NULL, text.panel = textPanel,
              label.pos = 0.5 + has.diag/3,
              cex.labels = NULL, font.labels = 1,
              row1attop = TRUE, gap = 1)
}
\usage{
pairs(x, \dots)

\method{pairs}{formula}(formula, data = NULL, \dots, subset)

\method{pairs}{default}(x, labels, panel = points, \dots,
      lower.panel = panel, upper.panel = panel,
      diag.panel = NULL, text.panel = textPanel,
      label.pos = 0.5 + has.diag/3,
      cex.labels = NULL, font.labels = 1,
      row1attop = TRUE, gap = 1)
}
\arguments{
  \item{x}{the coordinates of points given as columns of a matrix.}
  \item{formula}{a formula, such as \code{~ x + y + z}.  Each term will
    give a separate variable in the pairs plot, so terms should be
    numeric vectors.  (A response will be interpreted as another
    variable, but not treated specially, so it is confusing to use one.)}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used for plotting.}
  \item{labels}{the names of the variables.}
  \item{panel}{\code{function(x,y,\dots)} which is used to plot
    the contents of each panel of the display.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{plot}.}
  \item{lower.panel, upper.panel}{separate panel functions to be used
    below and above the diagonal respectively.}
  \item{diag.panel}{optional \code{function(x, \dots)} to be
    applied on the diagonals.}
  \item{text.panel}{optional \code{function(x, y, labels, cex,
      font, \dots)} to be applied on the diagonals.}
  \item{label.pos}{\code{y} position of labels in the text panel.}
  \item{cex.labels, font.labels}{graphics parameters for the text panel.}
  \item{row1attop}{logical. Should the layout be matrix-like with row 1
    at the top, or graph-like with row 1 at the bottom?}
  \item{gap}{Distance between subplots, in margin lines.}
}
\details{
  The \eqn{ij}th scatterplot contains \code{x[,i]} plotted against
  \code{x[,j]}.  The \dQuote{scatterplot} can be customised by setting panel
  functions to appear as something completely different. The
  off-diagonal panel functions are passed the appropriate columns of
  \code{x} as \code{x} and \code{y}: the diagonal panel function (if
  any) is passed a single column, and the \code{text.panel} function is
  passed a single \code{(x, y)} location and the column name.

  The graphical parameters \code{pch} and \code{col} can be used to
  specify a vector of plotting symbols and colors to be used in the
  plots.

  The graphical parameter \code{oma} will be set by \code{pairs.default}
  unless supplied as an argument.

  A panel function should not attempt to start a new plot, but just plot
  within a given coordinate system: thus \code{plot} and \code{boxplot}
  are not panel functions.

  For the default method, missing values are passed to the panel
  functions and will often be ignored within a panel.  However, for the
  formula method and the default value of \code{\link{na.action}}, all
  cases which contain a missing values for any of the variables are
  omitted completely (including when the scales are selected).  [The
  behaviour of the formula method will be changed in R 2.0.0.]
}
\author{
  Enhancements for \R 1.0.0 contributed by Dr. Jens
  Oehlschlaegel-Akiyoshi and R-core members.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(iris)
pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
      pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])

## formula method
data(swiss)
pairs(~ Fertility + Education + Catholic, data = swiss,
      subset = Education < 20, main = "Swiss data, Education < 20")

data(USJudgeRatings)
pairs(USJudgeRatings)

## put histograms on the diagonal
panel.hist <- function(x, ...)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(usr[1:2], 0, 1.5) )
    h <- hist(x, plot = FALSE)
    breaks <- h$breaks; nB <- length(breaks)
    y <- h$counts; y <- y/max(y)
    rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...)
}
pairs(USJudgeRatings[1:5], panel=panel.smooth,
      cex = 1.5, pch = 24, bg="light blue",
      diag.panel=panel.hist, cex.labels = 2, font.labels=2)

## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
panel.cor <- function(x, y, digits=2, prefix="", cex.cor)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r <- abs(cor(x, y))
    txt <- format(c(r, 0.123456789), digits=digits)[1]
    txt <- paste(prefix, txt, sep="")
    if(missing(cex.cor)) cex <- 0.8/strwidth(txt)
    text(0.5, 0.5, txt, cex = cex * r)
}
pairs(USJudgeRatings, lower.panel=panel.smooth, upper.panel=panel.cor)
}
\keyword{hplot}
\eof
\name{palette}
\title{Set or View the Graphics Palette}
\usage{
palette(value)
}
\alias{palette}
\arguments{
  \item{value}{an optional character vector.}
}
\description{
  View or manipulate the color palette which is used when a \code{col=}
  has a numeric index.
}
\details{
  If \code{value} has length 1, it is taken to be the name of
  a built in color palette.  If \code{value} has length greater
  than 1 it is assumed to contain a description of the colors
  which are to make up the new palette (either by name or
  by RGB levels).
  
  If \code{value} is omitted or has length 0, no change is made
  the current palette.

  Currently, the only built-in palette is \code{"default"}.
}
\value{
  The palette which \emph{was} in effect.  This is \code{\link{invisible}}
  unless the argument is omitted.
}
\seealso{
  \code{\link{colors}} for the vector of built-in \dQuote{named} colors;
  \code{\link{hsv}}, \code{\link{gray}}, \code{\link{rainbow}},
  \code{\link{terrain.colors}},\dots to construct colors;
  
  \code{\link{col2rgb}} for translating colors to RGB 3-vectors.
}
\examples{
palette()               # obtain the current palette
palette(rainbow(6))     # six color rainbow

(palette(gray(seq(0,.9,len=25)))) # gray scales; print old palette
matplot(outer(1:100,1:30), type='l', lty=1,lwd=2, col=1:30,
        main = "Gray Scales Palette",
        sub = "palette(gray(seq(0,.9,len=25)))")
palette("default")      # reset back to the default
}
\keyword{color}
\keyword{sysdata}
\eof
\name{Palettes}
\alias{rainbow}
\alias{heat.colors}
\alias{terrain.colors}
\alias{topo.colors}
\alias{cm.colors}
\title{Color Palettes}
\description{
  Create a vector of \code{n} \dQuote{contiguous} colors.
}
\usage{
rainbow(n, s = 1, v = 1, start = 0, end = max(1,n - 1)/n, gamma = 1)
heat.colors(n)
terrain.colors(n)
topo.colors(n)
cm.colors(n)
}
\arguments{
  \item{n}{the number of colors (\eqn{\ge 1}{>= 1}) to be in the
    palette.}
  \item{s,v}{the \dQuote{saturation} and \dQuote{value} to be used to complete the
    HSV color descriptions.}
  \item{start}{the (corrected) hue in [0,1] at which the rainbow
    begins.}
  \item{end}{the (corrected) hue in [0,1] at which the rainbow ends.}
  \item{gamma}{the gamma correction, see argument \code{gamma} in
    \code{\link{hsv}}.}
}
\details{
  Conceptually, all of these functions actually use (parts of) a line
  cut out of the 3-dimensional color space, parametrized by
  \code{\link{hsv}(h,s,v, gamma)}, where \code{gamma}\eqn{=1} for the
  \emph{foo}\code{.colors} function, and hence,
  equispaced hues in RGB space tend to cluster at
  the red, green and blue primaries.

  Some applications such as contouring require a palette
  of colors which do not \dQuote{wrap around} to give a final
  color close to the starting one.

  With \code{rainbow}, the parameters \code{start} and \code{end} can be used
  to specify particular subranges of hues.
  The following values can be used when generating such a subrange:
  red=0, yellow=\eqn{\frac 1 6}{1/6}, green=\eqn{\frac 2 6}{2/6},
  cyan=\eqn{\frac 3 6}{3/6}, blue=\eqn{\frac 4 6}{4/6}
  and magenta=\eqn{\frac 5 6}{5/6}.
}
\value{A character vector, \code{cv}, of color names.  This can be used
  either to create a user--defined color palette for subsequent
  graphics by \code{\link{palette}(cv)}, a \code{col=} specification
  in graphics functions or in \code{par}.
}
\seealso{
  \code{\link{colors}}, \code{\link{palette}},  \code{\link{hsv}},
  \code{\link{rgb}}, \code{\link{gray}} and \code{\link{col2rgb}} for
  translating to RGB numbers.
}
\examples{
# A Color Wheel
pie(rep(1,12), col=rainbow(12))

##------ Some palettes ------------
demo.pal <-
  function(n, border = if (n<32) "light gray" else NA,
           main = paste("color palettes;  n=",n),
           ch.col = c("rainbow(n, start=.7, end=.1)", "heat.colors(n)",
                      "terrain.colors(n)", "topo.colors(n)", "cm.colors(n)"))
{
    nt <- length(ch.col)
    i <- 1:n; j <- n / nt; d <- j/6; dy <- 2*d
    plot(i,i+d, type="n", yaxt="n", ylab="", main=main)
    for (k in 1:nt) {
        rect(i-.5, (k-1)*j+ dy, i+.4, k*j,
             col = eval(parse(text=ch.col[k])), border = border)
        text(2*j,  k * j +dy/4, ch.col[k])
    }
}
n <- if(.Device == "postscript") 64 else 16
     # Since for screen, larger n may give color allocation problem
demo.pal(n)
}
\keyword{color}
\keyword{dplot}
\eof
\name{panel.smooth}
\alias{panel.smooth}
\title{Simple Panel Plot}
\description{
  An example of a simple useful \code{panel} function to be used as
  argument in e.g., \code{\link{coplot}} or \code{\link{pairs}}.
}
\usage{
panel.smooth(x, y, col = par("col"), bg = NA, pch = par("pch"), cex = 1,
             col.smooth = "red", span = 2/3, iter=3, \dots)
}
\arguments{
  \item{x,y}{numeric vectors of the same length}
  \item{col,bg,pch,cex}{numeric or character codes for the color(s),
    point type and size of \code{\link{points}}; see also
    \code{\link{par}}.}
  \item{col.smooth}{color to be used by \code{lines} for drawing the
    smooths.}
  \item{span}{smoothing parameter \code{f} for \code{\link[stats]{lowess}}, see
    there.}
  \item{iter}{number of robustness iterations for \code{\link[stats]{lowess}}.}
  \item{\dots}{further arguments to \code{\link{lines}}.}
}
\seealso{
  \code{\link{coplot}} and \code{\link{pairs}} where \code{panel.smooth}
  is typically used;
  \code{\link[stats]{lowess}}.
}
\examples{
data(swiss)
pairs(swiss, panel = panel.smooth, pch = ".")# emphasize the smooths
pairs(swiss, panel = panel.smooth, lwd = 2, cex= 1.5, col="blue")# hmm...
}
\keyword{hplot}
\keyword{dplot}
\eof
\name{par}
\alias{par}
\alias{.Pars}
\alias{.Pars.readonly}
\title{Set or Query Graphical Parameters}

%% The 'real documentation' is the code	in ../../../main/par.c
%% AND (defined AND commented)		in ../../../include/Graphics.h
%% Default initialization by GInit()	in ../../../main/graphics.c

\description{
  \code{par} can be used to set or query graphical parameters.
  Parameters can be set by specifying them as arguments to \code{par} in
  \code{tag = value} form, or by passing them as a list of tagged
  values.
}
\usage{
par(\dots, no.readonly = FALSE)

<highlevel plot> (\dots, <tag> = <value>)
}

\arguments{
  \item{\dots}{arguments in \code{tag = value} form, or a list of tagged
    values.  The tags must come from the graphical parameters described
    below.}
  \item{no.readonly}{logical; if \code{TRUE} and there are no other
    arguments, only parameters are returned which can be set by a
    subsequent \code{par()} call.}
}

\details{
  Parameters are queried by giving one or more character vectors to
  \code{par}.

  \code{par()} (no arguments) or \code{par(no.readonly=TRUE)} is used to
  get \emph{all} the graphical parameters (as a named list).  Their
  names are currently taken from the variable \code{.Pars}.
  \code{.Pars.readonly} contains the names of the \code{par} arguments
  which are \emph{readonly}.

  \emph{\bold{R.O.}} indicates \emph{\bold{read-only arguments}}: These
  may only be used in queries, i.e., they do \emph{not} set anything.

  All but these \emph{\bold{R.O.}} and the following
  \emph{\bold{low-level arguments}} can be set as well in high-level and
  mid-level plot functions, such as \code{\link{plot}},
  \code{\link{points}}, \code{\link{lines}}, \code{\link{axis}},
  \code{\link{title}}, \code{\link{text}}, \code{\link{mtext}}:
  \itemize{
    \item \code{"ask"}
    \item \code{"fig"}, \code{"fin"}
    \item \code{"mai"}, \code{"mar"}, \code{"mex"}
    \item \code{"mfrow"}, \code{"mfcol"}, \code{"mfg"}
    \item \code{"new"}
    \item \code{"oma"}, \code{"omd"}, \code{"omi"}
    \item \code{"pin"}, \code{"plt"}, \code{"ps"}, \code{"pty"}
    \item \code{"usr"}
    \item \code{"xlog"}, \code{"ylog"}
  }
}

\value{
  When parameters are set, their former values are returned in an
  invisible named list.  Such a list can be passed as an argument to
  \code{par} to restore the parameter values.
  Use \code{par(no.readonly = TRUE)} for the full list of parameters
  that can be restored.

  When just one parameter is queried, the value is a character string.
  When two or more parameters are queried, the result is a list of
  character strings, with the list names giving the parameters.

  Note the inconsistency: setting one parameter returns a list, but
  querying one parameter returns a vector.
}

\section{Graphical Parameters}{
  \describe{
    \item{\code{adj}}{The value of \code{adj} determines the way in
      which text strings are justified.  A value of \code{0} produces
      left-justified text, \code{0.5} centered text and \code{1}
      right-justified text.  (Any value in \eqn{[0, 1]} is allowed, and
      on most devices values outside that interval will also work.)
      Note that the \code{adj} argument of \code{\link{text}} also
      allows \code{adj = c(x, y)} for different adjustment in x- and y-
      direction.}
    \item{\code{ann}}{If set to \code{FALSE}, high-level plotting
      functions do not annotate the plots they produce with axis and
      overall titles.  The default is to do annotation.}
    \item{\code{ask}}{logical.  If \code{TRUE}, the user is asked for
      input, before a new figure is drawn.}
    \item{\code{bg}}{The color to be used for the background of plots.
      A description of how colors are specified is given below.}
    \item{\code{bty}}{A character string which determined the type of
      box which is drawn about plots.  If \code{bty} is one of
      \code{"o"}, \code{"l"}, \code{"7"}, \code{"c"}, \code{"u"}, or
      \code{"]"} the resulting box resembles the corresponding upper
      case letter.  A value of \code{"n"} suppresses the box.}
    \item{\code{cex}}{A numerical value giving the amount by which
      plotting text and symbols should be scaled relative to the
      default.}
    \item{\code{cex.axis}}{The magnification to be used for axis
      annotation relative to the current.}
    \item{\code{cex.lab}}{The magnification to be used for x and y
      labels relative to the current.}
    \item{\code{cex.main}}{The magnification to be used for main titles
      relative to the current.}
    \item{\code{cex.sub}}{The magnification to be used for sub-titles
      relative to the current.}
    \item{\code{cin}}{\emph{\bold{R.O.}}; character size
      \code{(width,height)} in inches.}
    \item{\code{col}}{A specification for the default plotting color.  A
      description of how colors are specified is given below.}
    \item{\code{col.axis}}{The color to be used for axis annotation.}
    \item{\code{col.lab}}{The color to be used for x and y labels.}
    \item{\code{col.main}}{The color to be used for plot main titles.}
    \item{\code{col.sub}}{The color to be used for plot sub-titles.}
    \item{\code{cra}}{\emph{\bold{R.O.}}; size of default character
      \code{(width,height)} in \dQuote{rasters} (pixels).}
    \item{\code{crt}}{A numerical value specifying (in degrees) how
      single characters should be rotated.  It is unwise to expect
      values other than multiples of 90 to work.  Compare with
      \code{srt} which does string rotation.}
    \item{\code{csi}}{\emph{\bold{R.O.}}; height of (default sized)
      characters in inches.}
    \item{\code{cxy}}{\emph{\bold{R.O.}}; size of default character
      \code{(width,height)} in user coordinate units.
      \code{par("cxy")} is \code{par("cin")/par("pin")} scaled to user
      coordinates.
      Note that \code{c(\link{strwidth}(ch), \link{strheight}(ch))} for
      a given string \code{ch} is usually much more precise.}
    \item{\code{din}}{\emph{\bold{R.O.}}; the device dimensions,
      \code{(width,height)}, in inches.}
    \item{\code{err}}{(\emph{Unimplemented}; \R is silent when points
      outside the plot region are \emph{not} plotted.)
      The degree of error reporting desired.}
    \item{\code{fg}}{The color to be used for the foreground of plots.
      This is the default color used for things like axes and boxes
      around plots.  A description of how colors are specified is given
      below.}
    \item{\code{fig}}{A numerical vector of the form \code{c(x1, x2, y1,
	y2)} which gives the (NDC) coordinates of the figure region in
      the display region of the device. If you set this, unlike S, you
      start a new plot, so to add to an existing plot use
      \code{new=TRUE} as well.}
    \item{\code{fin}}{The figure region dimensions,
      \code{(width,height)}, in inches. If you set this, unlike S, you
      start a new plot.}
    \item{\code{font}}{An integer which specifies which font to use for
      text.  If possible, device drivers arrange so that 1 corresponds
      to plain text, 2 to bold face, 3 to italic and 4 to bold italic.}
    \item{\code{font.axis}}{The font to be used for axis annotation.}
    \item{\code{font.lab}}{The font to be used for x and y labels.}
    \item{\code{font.main}}{The font to be used for plot main titles.}
    \item{\code{font.sub}}{The font to be used for plot sub-titles.}
    \item{\code{gamma}}{the gamma correction, see argument \code{gamma}
      to \code{\link{hsv}}.}
    \item{\code{lab}}{A numerical vector of the form \code{c(x, y, len)}
      which modifies the way that axes are annotated.  The values of
      \code{x} and \code{y} give the (approximate) number of tickmarks
      on the x and y axes and \code{len} specifies the label size.  The
      default is \code{c(5, 5, 7)}.
      \emph{Currently}, \code{len} \emph{is unimplemented}.}
    \item{\code{las}}{numeric in \{0,1,2,3\}; the style of axis labels.
      \describe{
	\item{0:}{always parallel to the axis [\emph{default}],}
	\item{1:}{always horizontal,}
	\item{2:}{always perpendicular to the axis,}
	\item{3:}{always vertical.}
      }
      Note that other string/character rotation (via argument \code{srt}
      to \code{par}) does \emph{not} affect the axis labels.
    }
    \item{\code{lty}}{The line type.
      Line types can either be specified as an integer (0=blank,
      1=solid, 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or
      as one of the character strings \code{"blank"}, \code{"solid"},
      \code{"dashed"}, \code{"dotted"}, \code{"dotdash"},
      \code{"longdash"}, or \code{"twodash"}, where \code{"blank"} uses
      \sQuote{invisible lines} (i.e., doesn't draw them).

      Alternatively, a string of up to 8 characters (from \code{c(1:9,
	"A":"F")}) may be given, giving the length of line segments
      which are alternatively drawn and skipped.  See section
      \sQuote{Line Type Specification} below.}
    \item{\code{lwd}}{The line width, a \emph{positive} number,
      defaulting to \code{1}.}
    \item{\code{mai}}{A numerical vector of the form \code{c(bottom,
	left, top, right)} which gives the margin size specified in
      inches.}
    \item{\code{mar}}{A numerical vector of the form \code{c(bottom,
	left, top, right)} which gives the lines of margin to be
      specified on the four sides of the plot.
      The default is \code{c(5, 4, 4, 2) + 0.1}.}
    \item{\code{mex}}{\code{mex} is a character size expansion factor
      which is used to describe coordinates in the margins of plots.}
    \item{\code{mfcol, mfrow}}{A vector of the form \code{c(nr, nc)}.
      Subsequent figures will be drawn in an \code{nr}-by-\code{nc}
      array on the device by \emph{columns} (\code{mfcol}), or
      \emph{rows} (\code{mfrow}), respectively.

      In a layout with exactly two rows and columns the base value of
      \code{"cex"} is reduced by a factor of 0.83: if there are three or
      more of either rows or columns, the reduction factor is 0.66.

      Consider the alternatives, \code{\link{layout}} and
      \code{\link{split.screen}}.
    }
    \item{\code{mfg}}{A numerical vector of the form \code{c(i, j)}
      where \code{i} and \code{j} indicate which figure in an array of
      figures is to be drawn next (if setting) or is being drawn (if
      enquiring).  The array must already have been set by \code{mfcol}
      or \code{mfrow}.

      For compatibility with S, the form \code{c(i, j, nr, nc)} is also
      accepted, when \code{nr} and \code{nc} should be the current
      number of rows and number of columns.  Mismatches will be ignored,
      with a warning.}
    \item{\code{mgp}}{The margin line (in \code{mex} units) for the axis
      title, axis labels and axis line.
      The default is \code{c(3, 1, 0)}.}
    \item{\code{mkh}}{The height in inches of symbols to be drawn when
      the value of \code{pch} is an integer.
      %% <FIXME>
      \emph{Completely ignored currently}.
      %% </FIXME>
    }
    \item{\code{new}}{logical, defaulting to \code{FALSE}.  If set to
      \code{TRUE}, the next high-level plotting command (actually
      \code{\link{plot.new}}) should \emph{not clean} the frame before
      drawing \dQuote{as if it was on a \bold{\emph{new}} device}.}
    \item{\code{oma}}{A vector of the form \code{c(bottom, left, top,
	right)} giving the size of the outer margins in lines of text.}
    \item{\code{omd}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the outer margin region in NDC (= normalized device
      coordinates), i.e., as fraction (in \eqn{[0,1]}) of the device
      region.}
    \item{\code{omi}}{A vector of the form \code{c(bottom, left, top,
	right)} giving the size of the outer margins in inches.}
    \item{\code{pch}}{Either an integer specifying a symbol or a single
      character to be used as the default in plotting points. }
    \item{\code{pin}}{The current plot dimensions, \code{(width,height)},
      in inches.}
    \item{\code{plt}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the coordinates of the plot region as fractions of the
      current figure region.}
    \item{\code{ps}}{integer; the pointsize of text and symbols.}
    \item{\code{pty}}{A character specifying the type of plot region to
      be used; \code{"s"} generates a square plotting region and
      \code{"m"} generates the maximal plotting region.}
    \item{\code{smo}}{(\emph{Unimplemented}) a value which indicates how
      smooth circles and circular arcs should be.}
    \item{\code{srt}}{The string rotation in degrees.  See the comment
      about \code{crt}.
      %% NOT true for R (but for S): Causes \code{srt} to be set to the
      %% same value.
    }
    \item{\code{tck}}{The length of tick marks as a fraction of the
      smaller of the width or height of the plotting region.
      If \code{tck >= 0.5} it is interpreted as a fraction of the
      relevant side, so if
      \code{tck=1} grid lines are drawn.  The default setting
      (\code{tck = NA}) is to use \code{tcl = -0.5} (see below).}
    \item{\code{tcl}}{The length of tick marks as a fraction of the
      height of a line of text.  The default value is \code{-0.5};
      setting \code{tcl = NA} sets \code{tck = -0.01} which is S' default.}
    \item{\code{tmag}}{A number specifying the enlargement of text of
      the main title relative to the other annotating text of the plot.}
    \item{\code{type}}{character;  the default plot type desired, see
      \code{\link{plot.default}(type=\dots)}, defaulting to \code{"p"}.}
    \item{\code{usr}}{A vector of the form \code{c(x1, x2, y1, y2)}
      giving the extremes of the user coordinates of the plotting
      region.  When a logarithmic scale is in use (i.e.,
      \code{par("xlog")} is true, see below), then the x-limits will be
      \code{10 ^ par("usr")[1:2]}.  Similarly for the y-axis.
    }
    \item{\code{xaxp}}{A vector of the form \code{c(x1, x2, n)} giving
      the coordinates of the extreme tick marks and the number of
      intervals between tick-marks when \code{par("xlog")} is false.
      Otherwise, when \emph{log} coordinates are active, the three
      values have a different meaning: For a small range, \code{n} is
      \emph{negative}, and the ticks are as in the linear case,
      otherwise, \code{n} is in \code{1:3}, specifying a case number,
      and \code{x1} and \code{x2} are the lowest and highest power of 10
      inside the user coordinates, \code{10 ^ par("usr")[1:2]}. (The
      \code{"usr"} coordinates are log10-transformed here!)

      \describe{
	\item{n=1}{will produce tick marks at \eqn{10^j} for
	  integer \eqn{j},}
	\item{n=2}{gives marks  \eqn{k 10^j} with \eqn{k \in \{1, 5\}},}
	\item{n=3}{gives marks  \eqn{k 10^j} with \eqn{k \in \{1, 2, 5\}}.}
      }
      See \code{\link{axTicks}()} for a pure \R implementation of this.
    }
    \item{\code{xaxs}}{The style of axis interval calculation to be used
      for the x-axis.  Possible values are \code{"r"}, \code{"i"},
      \code{"e"}, \code{"s"}, \code{"d"}.  The styles are generally
      controlled by the range of data or \code{xlim}, if given.
      Style \code{"r"} (regular) first extends the data range by 4
      percent and then finds an axis with pretty labels that fits within
      the range.
      Style \code{"i"} (internal) just finds an axis with pretty labels
      that fits within the original data range.
      Style \code{"s"} (standard) finds an axis with pretty labels
      within which the original data range fits.
      Style \code{"e"} (extended) is like style \code{"s"}, except that
      it is also ensured that there is room for plotting symbols within
      the bounding box.
      Style \code{"d"} (direct) specifies that the current axis should
      be used on subsequent plots.
      (\emph{Only \code{"r"} and \code{"i"} styles are currently
	implemented})}
    \item{\code{xaxt}}{A character which specifies the axis type.
      Specifying \code{"n"} causes an axis to be set up, but not
      plotted.  The standard value is \code{"s"}: for compatibility with
      S values \code{"l"} and \code{"e"} are accepted but are equivalent
      to \code{"s"}.}
    \item{\code{xlog}}{logical value (see \code{log} in
      \code{\link{plot.default}}).  If \code{TRUE}, a logarithmic scale
      is in use (e.g., after \code{plot(*, log = "x")}).
      For a new device, it defaults to \code{FALSE}, i.e., linear scale.}
    \item{\code{xpd}}{A logical value or \code{NA}.
      If \code{FALSE}, all plotting is clipped to the plot region, if
      \code{TRUE}, all plotting is clipped to the figure region, and if
      \code{NA}, all plotting is clipped to the device region.}
    \item{\code{yaxp}}{A vector of the form \code{c(y1, y2, n)} giving
      the coordinates of the extreme tick marks and the number of
      intervals between tick-marks unless for log coordinates, see
      \code{xaxp} above.}
    \item{\code{yaxs}}{The style of axis interval calculation to be used
      for the y-axis.  See \code{xaxs} above.}
    \item{\code{yaxt}}{A character which specifies the axis type.
      Specifying \code{"n"} causes an axis to be set up, but not plotted.}
    \item{\code{ylog}}{a logical value; see \code{xlog} above.}
  }
}

\section{Color Specification}{
  Colors can be specified in several different ways. The simplest way is
  with a character string giving the color name (e.g., \code{"red"}).  A
  list of the possible colors can be obtained with the function
  \code{\link{colors}}. Alternatively, colors can be specified directly in
  terms of their RGB components with a string of the form \code{"#RRGGBB"}
  where each of the pairs \code{RR}, \code{GG}, \code{BB} consist of two
  hexadecimal digits giving a value in the range \code{00} to \code{FF}.
  Colors can also be specified by giving an index into a small table of
  colors, the \code{\link{palette}}.  This provides compatibility with
  S.  Index \code{0} corresponds to the background color.

  Additionally, \code{"transparent"} or (integer) \code{NA} is
  \emph{transparent}, useful for filled areas (such as the background!),
  and just invisible for things like lines or text.

  The functions \code{rgb}, \code{hsv}, \code{gray} and \code{rainbow}
  provide additional ways of generating colors.}

\section{Line Type Specification}{
  Line types can either be specified by giving an index into a small
  built in table of line types (1 = solid, 2 = dashed, etc, see
  \code{lty} above) or directly as the lengths of on/off stretches of
  line.  This is done with a string of an even number (up to eight)
  of characters, namely non-zero
  (hexadecimal) digits which give the lengths in consecutive positions
  in the string.  For example, the string \code{"33"} specifies three
  units on followed by three off and \code{"3313"} specifies three units
  on followed by three off followed by one on and finally three off.
  The \sQuote{units} here are (on most devices) proportional to
  \code{lwd}, and with \code{lwd = 1} are in pixels or points.

  The five standard dash-dot line types (\code{lty = 2:6}) correspond to
  \code{c("44", "13", "1343", "73", "2262")}.

  Note that \code{NA} is not a valid value for \code{lty}.
}

\note{
  The effect of restoring all the (settable) graphics parameters as
  in the examples is hard to predict if the device has been resized.
  Several of them are attempting to set the same things in different
  ways, and those last in the alphabet will win.  In particular, the
  settings of \code{mai}, \code{mar}, \code{pin}, \code{plt} and
  \code{pty} interact, as do the outer margin settings, the figure
  layout and figure region size.
}

\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot.default}} for some high-level plotting parameters;
  \code{\link{colors}}, \code{\link{gray}}, \code{\link{rainbow}},
  \code{\link{rgb}};
  \code{\link{options}} for other setup parameters;
  graphic devices \code{\link{x11}}, \code{\link{postscript}} and
  setting up device regions by \code{\link{layout}} and
  \code{\link{split.screen}}.
}

\examples{
op <- par(mfrow = c(2, 2), # 2 x 2 pictures on one plot
          pty = "s")       # square plotting region,
                           # independent of device size

## At end of plotting, reset to previous settings:
par(op)

## Alternatively,
op <- par(no.readonly = TRUE) # the whole list of settable par's.
## do lots of plotting and par(.) calls, then reset:
par(op)

par("ylog") # FALSE
plot(1 : 12, log = "y")
par("ylog") # TRUE

plot(1:2, xaxs = "i") # 'inner axis' w/o extra space
stopifnot(par("xaxp")[1:2] == 1:2 &&
          par("usr") [1:2] == 1:2)

( nr.prof <-
  c(prof.pilots=16,lawyers=11,farmers=10,salesmen=9,physicians=9,
    mechanics=6,policemen=6,managers=6,engineers=5,teachers=4,
    housewives=3,students=3,armed.forces=1))
par(las = 3)
barplot(rbind(nr.prof)) # R 0.63.2: shows alignment problem
par(las = 0)# reset to default

## 'fg' use:
plot(1:12, type = "b", main="'fg' : axes, ticks and box in gray",
     fg = gray(0.7), bty="7" , sub=R.version.string)

ex <- function() {
   old.par <- par(no.readonly = TRUE) # all par settings which
                                      # could be changed.
   on.exit(par(old.par))
   ## ...
   ## ... do lots of par() settings and plots
   ## ...
   invisible() #-- now,  par(old.par)  will be executed
}
ex()
}

\keyword{iplot}
\keyword{dplot}
\keyword{environment}
\eof
\name{pdf}
\alias{pdf}
\title{PDF Graphics Device}
%% The definitive doc is the source :-)
%% 	../../../main/devices.c  &   ../../../main/devPS.c
\description{
  \code{pdf} starts the graphics device driver for producing PDF
  graphics.
}
\synopsis{
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot\%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, title = "R Graphics Output", \dots)
}
\usage{
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot\%03d.pdf"),
    width = 6, height = 6, onefile = TRUE, family = "Helvetica",
    title = "R Graphics Output", encoding, bg, fg, pointsize)
}
\arguments{
  \item{file}{a character string giving the name of the file.}
  \item{width, height}{the width and height of the graphics region in
    inches.}
  \item{onefile}{logical: if true (the default) allow multiple figures
    in one file.  If false, generate a file name containing the page
    number.}
  \item{family}{the font family to be used, one of \code{"AvantGarde"},
    \code{"Bookman"}, \code{"Courier"}, \code{"Helvetica"},
    \code{"Helvetica-Narrow"}, \code{"NewCenturySchoolbook"},
    \code{"Palatino"} or \code{"Times"}. }
  \item{title}{title string to embed in the file.}
  \item{encoding}{the name of an encoding file.  Defaults to
#ifdef unix
\code{"ISOLatin1.enc"}
#endif
#ifdef windows
\code{"WinAnsi.enc"}
#endif
    in the \file{R\_HOME/afm} directory, which is used if the path does
    not contain a path separator.  An extension \code{".enc"} can be
    omitted.}
  \item{pointsize}{the default point size to be used.}
  \item{bg}{the default background color to be used.}
  \item{fg}{the default foreground color to be used.}
}
\details{
  \code{pdf()} opens the file \code{file} and the PDF commands needed to
  plot any graphics requested are sent to that file.

  See \code{\link{postscript}} for details of encodings, as the internal
  code is shared between the drivers.  The native PDF encoding is given
  in file \file{PDFDoc.enc}.

  \code{pdf} writes uncompressed PDF.  It is primarily intended for
  producing PDF graphics for inclusion in other documents, and
  PDF-includers such as \code{pdftex} are usually able to handle
  compression.

  At present the PDF is fairly simple, with each page being represented
  as a single stream.  The \R graphics model does not distinguish
  graphics objects at the level of the driver interface.
}
\note{
  Acrobat Reader does not use the fonts specified but rather emulates
  them from multiple-master fonts.  This can be seen in imprecise
  centering of characters, for example the multiply and divide signs in
  Helvetica.
}
\seealso{
  \code{\link{Devices}},
  \code{\link{postscript}}
}
\examples{
\dontrun{
## Test function for encodings
TestChars <- function(encoding="ISOLatin1")
{
    pdf(encoding=encoding)
    par(pty="s")
    plot(c(0,15), c(0,15), type="n", xlab="", ylab="")
    title(paste("Centred chars in encoding", encoding))
    grid(15, 15, lty=1)
    for(i in c(32:255)) {
	x <- i %% 16
	y <- i %/% 16
	points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings.
TestChars("ISOLatin2")
## doesn't view properly in US-spec Acrobat 5.05, but gs7.04 works.
## Lots of characters are not centred.
}}
\keyword{device}
\eof
\name{persp}
\alias{persp}
\alias{persp.default}
\title{Perspective Plots}
\description{
  This function draws perspective plots of surfaces over the
  x--y plane. \code{persp} is a generic function.
}
\usage{
persp(x, \dots)

\method{persp}{default}(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)), z,
      xlim = range(x), ylim = range(y), zlim = range(z, na.rm = TRUE),
      xlab = NULL, ylab = NULL, zlab = NULL, main = NULL, sub = NULL,
      theta = 0, phi = 15, r = sqrt(3), d = 1, scale = TRUE, expand = 1,
      col = "white", border = NULL, ltheta = -135, lphi = 0, shade = NA,
      box = TRUE, axes = TRUE, nticks = 5, ticktype = "simple",
      \dots)
}
\arguments{
  \item{x, y}{locations of grid lines at which the values in \code{z} are
    measured.  These must be in ascending order.  By default, equally
    spaced values from 0 to 1 are used.  If \code{x} is a \code{list},
    its components \code{x$x} and \code{x$y} are used for \code{x}
    and \code{y}, respectively.}
  \item{z}{a matrix containing the values to be plotted (\code{NA}s are
    allowed).  Note that \code{x} can be used instead of \code{z} for
    convenience.}
  \item{xlim, ylim, zlim}{x-, y-  and z-limits.  The plot is produced
    so that the rectangular volume defined by these limits is visible.}
  \item{xlab, ylab, zlab}{titles for the axes.  N.B. These must be
    character strings; expressions are not accepted.  Numbers will be
    coerced to character strings.}
  \item{main, sub}{main and sub title, as for \code{\link{title}}.}
  \item{theta, phi}{angles defining the viewing direction.
    \code{theta} gives the azimuthal direction and \code{phi}
    the colatitude.}
  \item{r}{the distance of the eyepoint from the centre of the plotting box.}
  \item{d}{a value which can be used to vary the strength of
    the perspective transformation.  Values of \code{d} greater
    than 1 will lessen the perspective effect and values less
    and 1 will exaggerate it.}
  \item{scale}{before viewing the x, y and z coordinates of the
    points defining the surface are transformed to the interval
    [0,1].  If \code{scale} is \code{TRUE} the x, y and z coordinates
    are transformed separately.  If \code{scale} is \code{FALSE}
    the coordinates are scaled so that aspect ratios are retained.
    This is useful for rendering things like DEM information.}
  \item{expand}{a expansion factor applied to the \code{z}
    coordinates. Often used with \code{0 < expand < 1} to shrink the
    plotting box in the \code{z} direction.}
  \item{col}{the color(s) of the surface facets.  Transparent colours are
    ignored.  This is recycled to the \eqn{(nx-1)(ny-1)} facets.}
  \item{border}{the color of the line drawn around the surface facets.
    A value of \code{NA} will disable the drawing of borders.  This is
    sometimes useful when the surface is shaded.}
  \item{ltheta, lphi}{if finite values are specified for \code{ltheta}
    and \code{lphi}, the surface is shaded as though it was being
    illuminated from the direction specified by azimuth \code{ltheta}
    and colatitude \code{lphi}.}
  \item{shade}{the shade at a surface facet is computed as
    \code{((1+d)/2)^shade}, where \code{d} is the dot product of
    a unit vector normal to the facet and a unit vector in the
    direction of a light source.  Values of \code{shade} close
    to one yield shading similar to a point light source model
    and values close to zero produce no shading.  Values in the
    range 0.5 to 0.75 provide an approximation to daylight
    illumination.}
  \item{box}{should the bounding box for the surface be displayed.
    The default is \code{TRUE}.}
  \item{axes}{should ticks and labels be added to the box.  The
    default is \code{TRUE}.  If \code{box} is \code{FALSE} then no
    ticks or labels are drawn.}
  \item{ticktype}{character: \code{"simple"} draws just an arrow
    parallel to the axis to indicate direction of increase;
    \code{"detailed"} draws normal ticks as per 2D plots.}
  \item{nticks}{the (approximate) number of tick marks to draw on the
    axes.  Has no effect if \code{ticktype} is \code{"simple"}.}
  \item{\dots}{additional graphical parameters (see \code{\link{par}}).}
}
\value{
  The \emph{viewing transformation matrix}, say \code{VT}, a
  \eqn{4 \times 4}{4 x 4} matrix suitable for projecting 3D coordinates
  \eqn{(x,y,z)} into the 2D plane using homogenous 4D coordinates
  \eqn{(x,y,z,t)}.
  It can be used to superimpose additional graphical elements on the 3D
  plot, by \code{\link{lines}()} or \code{\link{points}()}, e.g.
  using the function \code{trans3d} given in the last examples section
  below.
}
\details{
  The plots are produced by first transforming the
  coordinates to the interval [0,1].  The surface is then viewed
  by looking at the origin from a direction defined by \code{theta}
  and \code{phi}.  If \code{theta} and \code{phi} are both zero
  the viewing direction is directly down the negative y axis.
  Changing \code{theta} will vary the azimuth and changing \code{phi}
  the colatitude.

  There is a hook called \code{"persp"} (see \code{\link{setHook}})
  called after the plot is completed, which is used in the
  testing code to annotate the plot page.  The hook function(s) are
  called with no argument.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{contour}} and \code{\link{image}}.
}
\examples{
## More examples in  demo(persp) !!
##                   -----------

# (1) The Obligatory Mathematical surface.
#     Rotated sinc function.

x <- seq(-10, 10, length= 30)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
op <- par(bg = "white")
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
      ltheta = 120, shade = 0.75, ticktype = "detailed",
      xlab = "X", ylab = "Y", zlab = "Sinc( r )"
) -> res
round(res, 3)

# (2) Add to existing persp plot :

trans3d <- function(x,y,z, pmat) {
  tr <- cbind(x,y,z,1) \%*\% pmat
  list(x = tr[,1]/tr[,4], y= tr[,2]/tr[,4])
}
xE <- c(-10,10); xy <- expand.grid(xE, xE)
points(trans3d(xy[,1], xy[,2], 6, pm = res), col = 2, pch =16)
lines (trans3d(x, y=10, z= 6 + sin(x), pm = res), col = 3)

phi <- seq(0, 2*pi, len = 201)
r1 <- 7.725 # radius of 2nd maximum
xr <- r1 * cos(phi)
yr <- r1 * sin(phi)
lines(trans3d(xr,yr, f(xr,yr), res), col = "pink", lwd=2)## (no hidden lines)

# (3) Visualizing a simple DEM model

data(volcano)
z <- 2 * volcano        # Exaggerate the relief
x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
## Don't draw the grid lines :  border = NA
par(bg = "slategray")
persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
      ltheta = -120, shade = 0.75, border = NA, box = FALSE)
par(op)
}
\keyword{hplot}
\keyword{aplot}
\eof
\name{pictex}
\alias{pictex}
\title{A PicTeX Graphics Driver}
\usage{
pictex(file = "Rplots.tex", width = 5, height = 4, debug = FALSE,
       bg = "white", fg = "black")
}
\arguments{
  \item{file}{the file where output will appear.}
  \item{width}{The width of the plot in inches.}
  \item{height}{the height of the plot in inches.}
  \item{debug}{should debugging information be printed.}
  \item{bg}{the background color for the plot.}
  \item{fg}{the foreground color for the plot.}
}
\description{
  This function produces graphics suitable for inclusion in TeX and
  LaTeX documents.
}
\details{
  This driver does not have any font metric information, so the use of
  \code{\link{plotmath}} is not supported.

  Multiple plots will be placed as separate environments in the output file.
}
\references{
  Knuth, D. E. (1984)
  \emph{The TeXbook.}
  Reading, MA: Addison-Wesley.

  Lamport, L. (1994)
  \emph{LATEX: A Document Preparation System.}
  Reading, MA: Addison-Wesley.

  Goossens, M., Mittelbach, F. and Samarin, A. (1994)
  \emph{The LATEX Companion.}
  Reading, MA: Addison-Wesley.
}
\author{
  This driver was provided by Valerio Aimale
  \email{valerio@svpop.com.dist.unige.it}
  of the Department of Internal Medicine, University of Genoa, Italy.
}
\seealso{
  \code{\link{postscript}}, \code{\link{Devices}}.
}
\examples{
pictex()
plot(1:11,(-5:5)^2, type='b', main="Simple Example Plot")
dev.off()
##--------------------
\dontrun{
\%\% LaTeX Example
\\documentclass{article}
\\usepackage{pictex}
\\begin{document}
\%...
\\begin{figure}[h]
  \\centerline{\\input{Rplots.tex}}
  \\caption{}
\\end{figure}
\%...
\\end{document}

\%\%-- TeX Example --
\\input pictex
$$ \\input Rplots.tex $$
}
##--------------------
unlink("Rplots.tex")
}
\keyword{device}
%%-
%%--- on CTAN, searching for "pictex" in file FILES.byname  [April 3, 1998]:
% 1994/04/20 |        473 | graphics/pictex/addon/00index
% 1994/04/20 |       1568 | graphics/pictex/addon/piccorr.sty
% 1994/04/20 |       2952 | graphics/pictex/addon/picmore.tex
% 1994/04/20 |        311 | graphics/pictex/addon/pictex.sty
% 1994/04/20 |        416 | graphics/pictex/addon/pictexwd.sty
% 1994/04/20 |     133232 | graphics/pictex/addon/pictexwd.tex
% 1994/04/20 |        457 | graphics/pictex/addon/pictexzusatz.txt
% 1992/08/27 |       3041 | graphics/pictex/errorbars.tex
% 1992/08/27 |      10519 | graphics/pictex/latexpicobjs.tex
% 1992/08/27 |     129709 | graphics/pictex/pictex.tex
% 1992/08/27 |       1322 | graphics/pictex/pointers.tex
% 1992/08/27 |       1399 | graphics/pictex/postpictex.tex
% 1992/08/27 |       1082 | graphics/pictex/prepictex.tex
% 1992/08/27 |        175 | graphics/pictex/readme
% 1992/08/27 |        876 | graphics/pictex/readme.errorbars
% 1989/11/26 |       7270 | graphics/pictex/texpictex.tex
% 1992/08/31 |      11382 | graphics/pictex/tree.sty
% 1994/01/13 |        162 | info/stammtisch/wuppertal/updates/pictex.sty
% 1997/07/26 |      58723 | macros/context/generic/doc/m-pictex.pdf
% 1997/04/29 |       8053 | macros/context/generic/tex/m-pictex.tex
% 1997/08/20 |      58724 | macros/context/pictex/doc/m-pictex.pdf
% 1997/08/20 |       1261 | macros/context/pictex/doc/readme.de
% 1997/08/20 |       1207 | macros/context/pictex/doc/readme.en
% 1997/08/20 |       1323 | macros/context/pictex/doc/readme.nl
% 1997/08/20 |        145 | macros/context/pictex/tex/m-pictex.sty
% 1997/08/20 |       8689 | macros/context/pictex/tex/m-pictex.tex
% 1997/06/30 |         39 | macros/context/ppchtex/tex/m-pictex.sty
% 1997/04/29 |       8053 | macros/context/ppchtex/tex/m-pictex.tex
% 1994/01/14 |        162 | macros/latex209/contrib/konstruk/pictex.sty
% 1992/08/27 |       7251 | macros/plain/contrib/texpictex.tex
% 1991/07/29 |      27946 | support/pictex-converter/PiCUNIX.PASCAL
% 1991/07/25 |      23812 | support/pictex-converter/piccon1.uue
% 1991/07/25 |      25756 | support/pictex-converter/piccon2.uue
% 1991/07/25 |        379 | support/pictex-converter/picconv.anleit
% 1991/07/25 |      35840 | support/pictex-converter/picconv.lzh
% 1991/07/25 |       1906 | support/pictex-converter/pictex.info-cb
% 1991/07/25 |      54800 | support/pictex-converter/pictexte.exe
% 1991/07/25 |      43757 | support/pictex-converter/pictexte.pas
% 1992/08/25 |        835 | support/qfig/q-pictex.tex
% 1991/10/11 |      51141 | systems/atari/texutils/texdraw/pictex.tos
% 1995/07/13 |      45973 | systems/msdos/4alltex/disk04/pictex.zip
% 1995/06/26 |      39887 | systems/msdos/emtex/pictex.zip
% 1998/02/02 |        676 | systems/unix/linux/fastpictex-0.3.lsm
% 1998/02/02 |     309581 | systems/unix/linux/fastpictex-0.3.tar.gz
% 1997/01/27 |      73930 | systems/unix/teTeX/distrib/goodies/pictex.tar.gz
\eof
\name{pie}
\title{Pie Charts}
\alias{pie}
\description{
  Draw a pie chart.
}
\usage{
pie(x, labels = names(x), edges = 200, radius = 0.8,
    density = NULL, angle = 45, col = NULL, border = NULL, lty = NULL,
    main = NULL, \dots)
}
\arguments{
  \item{x}{a vector of positive quantities.
    The values in \code{x} are displayed as the areas of pie slices.}
  \item{labels}{a vector of character strings giving names for the
    slices.  For empty or NA labels, no pointing line is drawn either.}
  \item{edges}{the circular outline of the pie is approximated by a
    polygon with this many edges.}
  \item{radius}{the pie is drawn centered in a square box whose sides
    range from \eqn{-1} to \eqn{1}.  If the character strings labeling
    the slices are long it may be necessary to use a smaller radius.}
  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines
    are drawn. Non-positive values of \code{density} also inhibit the
    drawing of shading lines.}
  \item{angle}{the slope of shading lines, given as an angle in
    degrees (counter-clockwise).}
  \item{col}{a vector of colors to be used in filling or shading
    the slices. If missing a set of 6 pastel colours is used,
    unless \code{density} is specified when \code{par("fg")} is used.}
  \item{border, lty}{(possibly vectors) arguments passed to
    \code{\link{polygon}} which draws each slice.}
  \item{main}{an overall title for the plot.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{pie}.  They will affect the main title and labels only.}
}
\note{
  Pie charts are a very bad way of displaying information.
  The eye is good at judging linear measures and bad at judging
  relative areas.  A bar chart or dot chart is a preferable way of
  displaying this type of data.

  Cleveland (1985), page 264: \dQuote{Data that can be shown by pie charts
    always can be shown by a dot chart.  This means that judgements of
    position along a common scale can be made instead of the less
    accurate angle judgements.}
  This statement is based on the empirical investigations of Cleveland
  and McGill as well as investigations by perceptual psychologists.
  
  Prior to \R 1.5.0 this was known as \code{piechart}, which is the name
  of a Trellis function, so the name was changed to be compatible with S.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The elements of graphing data}.
  Wadsworth: Monterey, CA, USA.
}
\seealso{
  \code{\link{dotchart}}.
}
\examples{
pie(rep(1, 24), col = rainbow(24), radius = 0.9)

pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
names(pie.sales) <- c("Blueberry", "Cherry",
    "Apple", "Boston Cream", "Other", "Vanilla Cream")
pie(pie.sales) # default colours
pie(pie.sales,
    col = c("purple", "violetred1", "green3", "cornsilk", "cyan", "white"))
pie(pie.sales, col = gray(seq(0.4,1.0,length=6)))
pie(pie.sales, density = 10, angle = 15 + 10 * 1:6)

n <- 200
pie(rep(1,n), labels="", col=rainbow(n), border=NA,
    main = "pie(*, labels=\"\", col=rainbow(n), border=NA,..")
}
\keyword{hplot}
\eof
\name{plot}
\title{Generic X-Y Plotting}
\alias{plot}
\usage{
plot(x, y, \dots)
}
\arguments{
  \item{x}{the coordinates of points in the plot. Alternatively, a
      single plotting structure, function or \emph{any \R object with a
          \code{plot} method} can be provided.}
  \item{y}{the y coordinates of points in the plot, \emph{optional}
      if \code{x} is an appropriate structure.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{plot}.  Many methods will also accept the following arguments:

    \item{type}{what type of plot should be drawn.  Possible types are
      \itemize{
	\item \code{"p"} for \bold{p}oints,
	\item \code{"l"} for \bold{l}ines,
	\item \code{"b"} for \bold{b}oth,
	\item \code{"c"} for the lines part alone of \code{"b"},
	\item \code{"o"} for both \dQuote{\bold{o}verplotted},
	\item \code{"h"} for \dQuote{\bold{h}istogram} like (or
	\dQuote{high-density}) vertical lines,
	\item \code{"s"} for stair \bold{s}teps,
	\item \code{"S"} for other \bold{s}teps, see \emph{Details} below,
	\item \code{"n"} for no plotting.
      }
      All other \code{type}s give a warning or an error; using, e.g.,
      \code{type = "punkte"} being equivalent to \code{type = "p"} for S
      compatibility.
    }
    \item{main}{an overall title for the plot: see \code{\link{title}}.}
    \item{sub}{a sub title for the plot: see \code{\link{title}}.}
    \item{xlab}{a title for the x axis: see \code{\link{title}}.}
    \item{ylab}{a title for the y axis: see \code{\link{title}}.}
  }
}
\description{
  Generic function for plotting of \R objects.  For more details about
  the graphical parameter arguments, see \code{\link{par}}.
}
\details{
  For simple scatter plots, \code{\link{plot.default}} will be used.
  However, there are \code{plot} methods for many \R objects,
  including \code{\link{function}}s, \code{\link{data.frame}}s,
  \code{\link[stats]{density}} objects, etc.  Use \code{methods(plot)} and
  the documentation for these.

  The two step types differ in their x-y preference: Going from
  \eqn{(x1,y1)} to \eqn{(x2,y2)} with \eqn{x1 < x2}, \code{type = "s"}
  moves first horizontal, then vertical, whereas \code{type = "S"} moves
  the other way around.
}
\seealso{
  \code{\link{plot.default}}, \code{\link{plot.formula}} and other
  methods; \code{\link{points}}, \code{\link{lines}}, \code{\link{par}}.
}
\examples{
data(cars)
plot(cars)
lines(lowess(cars))

plot(sin, -pi, 2*pi)

## Discrete Distribution Plot:
plot(table(rpois(100,5)), type = "h", col = "red", lwd=10,
     main="rpois(100,lambda=5)")

## Simple quantiles/ECDF, see ecdf() {library(stats)} for a better one:
plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
points(x, cex = .5, col = "dark red")
}
\keyword{hplot}
\eof
\name{plot.data.frame}
\alias{plot.data.frame}
\title{Plot Method for Data Frames}
\description{
  \code{plot.data.frame}, a method of the \code{\link{plot}} generic,
  uses \code{\link{stripchart}} for \emph{one} variable,
  \code{\link{plot.default}} (scatterplot) for \emph{two} variables, and
  \code{\link{pairs}} (scatterplot matrix) otherwise.
}
\usage{
\method{plot}{data.frame}(x, \dots)
}
\arguments{
  \item{x}{object of class \code{data.frame}.}
  \item{\dots}{further arguments to \code{\link{stripchart}},
    \code{\link{plot.default}} or \code{\link{pairs}}.}
}
\seealso{
  \code{\link{data.frame}}
}
\examples{
data(OrchardSprays)
plot(OrchardSprays[1], method="jitter")
plot(OrchardSprays[c(4,1)])
plot(OrchardSprays)
}
\keyword{hplot}
\keyword{methods}
\eof
\name{plot.design}
\alias{plot.design}
\title{Plot Univariate Effects of a `Design' or Model}
\description{
  Plot univariate effects of one ore more \code{\link{factor}}s,
  typically for a designed experiment as analyzed by \code{\link[stats]{aov}()}.
  Further, in S this a method of the \code{\link{plot}} generic function
  for \code{design} objects.
}
\usage{
plot.design(x, y = NULL, fun = mean, data = NULL, \dots,
            ylim = NULL, xlab = "Factors", ylab = NULL, main = NULL,
            ask = NULL, xaxt = par("xaxt"), axes = TRUE, xtick = FALSE)
}
\arguments{
  \item{x}{either a data frame containing the design factors and
    optionally the response, or a \code{\link[stats]{formula}} or
    \code{\link[stats]{terms}} object.}
  \item{y}{the response, if not given in x.}
  \item{fun}{a function (or name of one) to be applied to each
    subset.  It must return one number for a numeric (vector) input.}
  \item{data}{data frame containing the variables referenced by \code{x}
    when that is formula like.}
  \item{\dots}{graphical arguments such as \code{col}, see \code{\link{par}}.}
  \item{ylim}{range of y values, as in \code{\link{plot.default}}.}
  \item{xlab}{x axis label, see \code{\link{title}}.}
  \item{ylab}{y axis label with a \dQuote{smart} default.}
  \item{main}{main title, see \code{\link{title}}.}
  \item{ask}{logical indicating if the user should be asked before a new
    page is started -- in the case of multiple y's.}
  \item{xaxt}{character giving the type of x axis.}
  \item{axes}{logical indicating if axes should be drawn.}
  \item{xtick}{logical indicating if \dQuote{ticks} (one per factor) should
    be drawn on the x axis.}
}
\details{
  The supplied function will be called once for each level of each
  factor in the design and the plot will show these summary values.  The
  levels of a particular factor are shown along a vertical line, and the
  overall value of \code{fun()} for the response is drawn as a
  horizontal line.

  This is a new \R implementation which will not be completely
  compatible to the earlier S implementations.  This is not a bug but
  might still change.
}
\references{
  Chambers, J. M. and Hastie, T. J. eds (1992)
  \emph{Statistical Models in S}.
  Chapman & Hall, London, \bold{the} \emph{white book}, pp. 546--7 (and 163--4).

  Freeny, A. E. and Landwehr, J. M. (1990)
  Displays for data from large designed experiments;
  Computer Science and Statistics: Proc.\ 22nd Symp\. Interface, 117--126,
  Springer Verlag.
}
\author{Roberto Frisullo and Martin Maechler}
\note{A big effort was taken to make this closely compatible to the S
  version.  However, \code{col} (and \code{fg}) specification has
  different effects.
}
\seealso{\code{\link[stats]{interaction.plot}} for a \dQuote{standard graphic}
  of designed experiments.}
\examples{
data(warpbreaks)
plot.design(warpbreaks)# automatic for data frame with one numeric var.

Form <- breaks ~ wool + tension
summary(fm1 <- aov(Form, data = warpbreaks))
plot.design(       Form, data = warpbreaks, col = 2)# same as above

## More than one y :
data(esoph)
utils::str(esoph)
plot.design(esoph) ## two plots; if interactive you are "ask"ed

## or rather, compare mean and median:
op <- par(mfcol = 1:2)
plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0,0.8))
plot.design(ncases/ncontrols ~ ., data = esoph, ylim = c(0,0.8), fun = median)
par(op)
}
\keyword{hplot}

\eof
\name{plot.table}
\alias{plot.table}
\title{Plot Methods for `table' Objects}
\description{
  This is a method of the generic \code{plot} function for
  (contingency) \code{\link{table}} objects.  Whereas for two- and more
  dimensional tables, a \code{\link{mosaicplot}} is drawn,
  one-dimensional ones are plotted \dQuote{bar like}.
}
\usage{
%% Improvement ideas: see code definition, currently in ../R/plot.R
\method{plot}{table}(x, type = "h", ylim = c(0, max(x)), lwd = 2,
      xlab = NULL, ylab = NULL, frame.plot = is.num, \dots)
}
\arguments{
  \item{x}{a \code{\link{table}} (like) object.}
  \item{type}{plotting type.}
  \item{ylim}{range of y-axis.}
  \item{lwd}{line width for bars when \code{type = "h"} is used in the 1D case.}
  \item{xlab, ylab}{x- and y-axis labels.}
  \item{frame.plot}{logical indicating if a frame (\code{\link{box}})
    should be drawn in the 1D case.  Defaults to true when \code{x} has
    \code{\link{dimnames}} coerceable to numbers.}
  \item{\dots}{further graphical arguments, see \code{\link{plot.default}}.}
}
\details{
  The current implementation (R 1.2) is somewhat experimental and will
  be improved and extended.
}
\seealso{\code{\link{plot.factor}}, the \code{\link{plot}} method for factors.}

\examples{
## 1-d tables
(Poiss.tab <- table(N = rpois(200, lam= 5)))
plot(Poiss.tab, main = "plot(table(rpois(200, lam=5)))")

data(state)
plot(table(state.division))

## 4-D :
data(Titanic)
plot(Titanic, main ="plot(Titanic, main= *)")

}
\keyword{hplot}
\keyword{category}
\eof
\name{plot.window}
\alias{plot.window}
\title{Set up World Coordinates for Graphics Window}
\description{
  This function sets up the world coordinate system for a graphics
  window.  It is called by higher level functions such as
  \code{\link{plot.default}} (\emph{after} \code{\link{plot.new}}).
}
\usage{
plot.window(xlim, ylim, log = "", asp = NA, \dots)
}
\arguments{
  \item{xlim, ylim}{numeric of length 2, giving the x and y coordinates
    ranges.}
  \item{log}{character; indicating which axes should be in log scale.}
  \item{asp}{numeric, giving the \bold{asp}ect ratio y/x.}
  \item{\dots}{further graphical parameters as in \code{\link{par}}.}
}
\details{
  Note that if \code{asp} is a finite positive value then the window is
  set up so that one data unit in the x direction is equal in length to
  \code{asp} \eqn{\times}{*} one data unit in the y direction.

  The special case \code{asp == 1} produces plots where distances
  between points are represented accurately on screen.  Values with
  \code{asp > 1} can be used to produce more accurate maps when using
  latitude and longitude.

  The function attempts to produce a plausible set of scales if one or
  both of \code{xlim} and \code{ylim} is of length one or the two values
  given are identical, but it is better to avoid that case.

  Usually, one should rather use the higher level functions such as
  \code{\link{plot}}, \code{\link{hist}}, \code{\link{image}}, \dots,
  instead and refer to their help pages for explanation of the
  arguments.
}
\seealso{
  \code{\link{xy.coords}},
  \code{\link{plot.xy}},
  \code{\link{plot.default}}.
}
\examples{
##--- An example for the use of 'asp' :
library(stats)  # normally loaded
data(eurodist)
loc <- cmdscale(eurodist)
rx <- range(x <- loc[,1])
ry <- range(y <- -loc[,2])
plot(x, y, type="n", asp=1, xlab="", ylab="")
abline(h = pretty(rx, 10), v = pretty(ry, 10), col = "lightgray")
text(x, y, names(eurodist), cex=0.8)
}
\keyword{aplot}
\eof
\name{plot.xy}
\alias{plot.xy}
\title{Basic Internal Plot Function}
\description{
  This is \emph{the} internal function that does the basic plotting of
  points and lines.  Usually, one should rather use the higher level
  functions instead and refer to their help pages for explanation of the
  arguments.
}
\usage{
plot.xy(xy, type, pch=1, lty="solid", col=par("fg"), bg=NA, cex=1, \dots)
}
\arguments{
  \item{xy}{A four-element list as results from
    \code{\link{xy.coords}}.}
  \item{type}{1 character code.}
  \item{pch}{character or integer code for kind of points/lines, see
    \code{\link{points.default}}.}
  \item{lty}{line type code, see \code{\link{lines}}.}
  \item{col}{color code or name, see \code{\link{colors}},
    \code{\link{palette}}.}
  \item{bg}{background (\dQuote{fill}) color for open plot symbols.}
  \item{cex}{character expansion.}
  \item{\dots}{further graphical parameters.}
}
\seealso{
  \code{\link{plot}},
  \code{\link{plot.default}},
  \code{\link{points}},
  \code{\link{lines}}.
}
\examples{
points.default # to see how it calls "plot.xy(xy.coords(x, y), ...)"
}
\keyword{aplot}
\eof
\name{plot.default}
\alias{plot.default}
\title{The Default Scatterplot Function}
\description{
  Draw a scatter plot with \dQuote{decorations} such as axes and titles
  in the active graphics window.
}
\usage{
\method{plot}{default}(x, y = NULL, type = "p",  xlim = NULL, ylim = NULL,
     log = "", main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
     ann = par("ann"), axes = TRUE, frame.plot = axes,
     panel.first = NULL, panel.last = NULL,
     col = par("col"), bg = NA, pch = par("pch"),
     cex = 1, lty = par("lty"), lab = par("lab"),
     lwd = par("lwd"), asp = NA, \dots)
}
\arguments{
  \item{x,y}{the \code{x} and \code{y} arguments provide the x and y
    coordinates for the plot.  Any reasonable way of defining the
    coordinates is acceptable.  See the function \code{\link{xy.coords}}
    for details.}
  \item{type}{1-character string giving the type of plot desired.  The
    following values are possible, for details, see \code{\link{plot}}:
    \code{"p"} for points, \code{"l"} for lines,
    \code{"o"} for overplotted points and lines,
    \code{"b"}, \code{"c"}) for (empty if \code{"c"}) points joined by lines,
    \code{"s"} and \code{"S"} for stair steps and
    \code{"h"} for histogram-like vertical lines.  Finally,
    \code{"n"} does not produce any points or lines.}
  \item{xlim}{the x limits (min,max) of the plot.}
  \item{ylim}{the y limits of the plot.}
  \item{log}{a character string which contains \code{"x"} if the x axis
    is to be logarithmic, \code{"y"} if the y axis is to be logarithmic
    and \code{"xy"} or \code{"yx"} if both axes are to be logarithmic.}

  \item{main}{a main title for the plot.}
  \item{sub}{a sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}

  \item{ann}{a logical value indicating whether the default annotation
    (title and x and y axis labels) should appear on the plot.}
  \item{axes}{a logical value indicating whether axes should be drawn on
    the plot.}
  \item{frame.plot}{a logical indicating whether a box should be drawn
    around the plot.}

  \item{panel.first}{an expression to be evaluated after the plot axes
    are set up but before any plotting takes place.  This can be useful
    for drawing background grids or scatterplot smooths.}
  \item{panel.last}{an expression to be evaluated after plotting has
    taken place.}

  \item{col}{The colors for lines and points.  Multiple colors can be
    specified so that each point can be given its own color.  If there
    are fewer colors than points they are recycled in the standard
    fashion.  Lines will all be plotted in the first colour specified.}
  \item{bg}{background color for open plot symbols, see
    \code{\link{points}}.}
  \item{pch}{a vector of plotting characters or symbols: see \code{\link{points}}.}
  \item{cex}{a numerical vector giving the amount by which plotting text
    and symbols should be scaled relative to the default.}
  \item{lty}{the line type, see \code{\link{par}}.}
  \item{lab}{the specification for the (approximate) numbers of tick
    marks on the x and y axes.}
  \item{lwd}{the positive line width.}
  \item{asp}{the \eqn{y/x} aspect ratio, see \code{\link{plot.window}}.}
  \item{\dots}{graphical parameters as in \code{\link{par}} may also be
    passed as arguments.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  Cleveland, W. S. (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, CA: Wadsworth.
}
\seealso{
  \code{\link{plot}}, \code{\link{plot.window}}, \code{\link{xy.coords}}.
}
\examples{
data(cars)
Speed <- cars$speed
Distance <- cars$dist
plot(Speed, Distance, panel.first = grid(8,8),
     pch = 0, cex = 1.2, col = "blue")
plot(Speed, Distance,
     panel.first = lines(lowess(Speed, Distance), lty = "dashed"),
     pch = 0, cex = 1.2, col = "blue")

## Show the different plot types
x <- 0:12
y <- sin(pi/5 * x)
op <- par(mfrow = c(3,3), mar = .1+ c(2,2,3,1))
for (tp in c("p","l","b",  "c","o","h",  "s","S","n")) {
   plot(y ~ x, type = tp,
        main = paste("plot(*, type = \"",tp,"\")",sep=""))
   if(tp == "S") {
      lines(x,y, type = "s", col = "red", lty = 2)
      mtext("lines(*, type = \"s\", ...)", col = "red", cex=.8)
   }
}
par(op)

##--- Log-Log Plot  with  custom axes
lx <- seq(1,5, length=41)
yl <- expression(e^{-frac(1,2) * {log[10](x)}^2})
y <- exp(-.5*lx^2)
op <- par(mfrow=c(2,1), mar=par("mar")+c(0,1,0,0))
plot(10^lx, y, log="xy", type="l", col="purple",
     main="Log-Log plot", ylab=yl, xlab="x")
plot(10^lx, y, log="xy", type="o", pch='.', col="forestgreen",
     main="Log-Log plot with custom axes", ylab=yl, xlab="x",
     axes = FALSE, frame.plot = TRUE)
axis(1, at = my.at <- 10^(1:5), labels = formatC(my.at, format="fg"))
at.y <- 10^(-5:-1)
axis(2, at = at.y, labels = formatC(at.y, format="fg"), col.axis="red")
par(op)
}
\keyword{hplot}
\eof
\name{plot.factor}
\title{Plotting Factor Variables}
\usage{
\method{plot}{factor}(x, y, legend.text = levels(y), \dots)
}
\alias{plot.factor}
\arguments{
    \item{x,y}{numeric or factor.  \code{y} may be missing.}
    \item{legend.text}{a vector of text used to construct a legend for
        the plot. Only used if \code{y} is present and a factor.}
    \item{\dots}{Further arguments to \code{\link{plot}}, see also
        \code{\link{par}}.}
}
\description{
  This functions implements a \dQuote{scatterplot} method for
  \code{\link{factor}} arguments of the \emph{generic}
  \code{\link{plot}} function.
  Actually, \code{\link{boxplot}} or \code{\link{barplot}} are used when
  appropriate.
}
\seealso{
    \code{\link{plot.default}}, \code{\link{plot.formula}},
    \code{\link{barplot}}, \code{\link{boxplot}}.
}
\examples{
data(PlantGrowth)
plot(PlantGrowth)                                # -> plot.data.frame
plot(weight ~ group, data = PlantGrowth)         # numeric vector ~ factor
plot(cut(weight, 2) ~ group, data = PlantGrowth) # factor ~ factor
## passing "..." to barplot() eventually:
plot(cut(weight, 3) ~ group, data = PlantGrowth, density = 16*(1:3),col=NULL)

plot(PlantGrowth$group, axes=FALSE, main="no axes")# extremly silly
}
\keyword{hplot}
\eof
\name{plot.formula}
\alias{plot.formula}
\alias{lines.formula}
\alias{points.formula}
\title{Formula Notation for Scatterplots}
\description{
  Specify a scatterplot or add points or lines via a formula.
}
\usage{
\method{plot}{formula}(formula, data = parent.frame(), \dots, subset,
             ylab = varnames[response], ask = TRUE)

\method{points}{formula}(formula, data = parent.frame(), \dots, subset)

\method{lines}{formula}(formula, data = parent.frame(), \dots, subset)
}
\arguments{
  \item{formula}{a \code{\link[stats]{formula}}, such as \code{y ~ x}.}
  \item{data}{a data.frame (or list) from which the variables in
    \code{formula} should be taken.}
  \item{\dots}{Further graphical parameters may also be passed as
    arguments, see \code{\link{par}}.  \code{horizontal = TRUE}
    is also accepted.}
  \item{subset}{an optional vector specifying a subset of observations
    to be used in the fitting process.}
  \item{ylab}{the y label of the plot(s).}
  \item{ask}{logical, see \code{\link{par}}.}
}
\details{
  Both the terms in the formula and the \code{\dots} arguments are
  evaluated in \code{data} enclosed in \code{parent.frame()} if
  \code{data} is a list or a data frame. The terms of the formula and
  those arguments in \code{\dots} that are of the same length as
  \code{data} are subjected to the subsetting specified in
  \code{subset}. If the formula in \code{plot.formula} contains more
  than one non-response term, a series of plots of y against each term
  is given.  A plot against the running index can be specified as
  \code{plot(y ~ 1)}.

  Missing values are not considered in these methods, and in particular
  cases with missing values are not removed.

  If \code{y} is an object (ie. has a \code{\link[base]{class}} attribute)
  then \code{plot.formula} looks for a plot method for that class first.
  Otherwise, the class of \code{x} will determine the type of the plot.
  For factors this will be a parallel boxplot, and argument
  \code{horizontal = TRUE} can be used (see \code{\link{boxplot}}).
}
\value{
  These functions are invoked for their side effect of drawing 
  in the active graphics device.
}
\seealso{
  \code{\link{plot.default}}, \code{\link{plot.factor}}.
}
\examples{
data(airquality)
op <- par(mfrow=c(2,1))
plot(Ozone ~ Wind, data = airquality, pch=as.character(Month))
plot(Ozone ~ Wind, data = airquality, pch=as.character(Month),
     subset = Month != 7)
par(op)
}
\keyword{hplot}
\eof
\name{plot.histogram}
\alias{plot.histogram}
\alias{lines.histogram}
\title{Plot Histograms}
\description{
  These are methods for objects of class \code{"histogram"}, typically
  produced by \code{\link{hist}}.
}
\usage{
\method{plot}{histogram}(x, freq = equidist, density = NULL, angle = 45,
               col = NULL, border = par("fg"), lty = NULL,
               main = paste("Histogram of", x$xname), sub = NULL,
               xlab = x$xname, ylab, xlim = range(x$breaks), ylim = NULL,
               axes = TRUE, labels = FALSE, add = FALSE, \dots)

\method{lines}{histogram}(x, \dots)
}
\arguments{
  \item{x}{a \code{histogram} object, or a list with components
    \code{density}, \code{mid}, etc, see \code{\link{hist}} for
    information about the components of \code{x}.}
  \item{freq}{logical; if \code{TRUE}, the
    histogram graphic is to present a representation of frequencies, i.e,
    \code{x$counts}; if \code{FALSE}, \emph{relative} frequencies
    (\dQuote{probabilities}), i.e., \code{x$density}, are plotted.  The
    default is true for equidistant \code{breaks} and false otherwise.}
  \item{col}{a colour to be used to fill the bars.  The default of
    \code{NULL} yields unfilled bars.}
  \item{border}{the color of the border around the bars.}
  \item{angle, density}{select shading of bars by lines:
    see \code{\link{rect}}.}
  \item{lty}{the line type used for the bars, see also \code{\link{lines}}.}
  \item{main, sub, xlab, ylab}{these arguments to \code{title} have useful
    defaults here.}
  \item{xlim, ylim}{the range of x and y values with sensible defaults.}
  \item{axes}{logical, indicating if axes should be drawn.}
  \item{labels}{logical or character.  Additionally draw labels on top of bars,
    if not \code{FALSE}; if \code{TRUE}, draw the counts or rounded
    densities; if \code{labels} is a \code{character}, draw itself.}
  \item{add}{logical.  If \code{TRUE}, only the bars are added to the
    current plot.  This is what \code{lines.histogram(*)} does.}
  \item{\dots}{further graphical parameters to \code{title} and \code{axis}.}
}
\details{
  \code{lines.histogram(*)} is the same as
  \code{plot.histogram(*, add = TRUE)}.
}
\seealso{
  \code{\link{hist}},
  \code{\link{stem}},
  \code{\link[stats]{density}}.
}
\examples{
data(women)
(wwt <- hist(women$weight, nc= 7, plot = FALSE))
plot(wwt, labels = TRUE) # default main & xlab using wwt$xname
plot(wwt, border = "dark blue", col = "light blue",
     main = "Histogram of 15 women's weights", xlab = "weight [pounds]")

## Fake "lines" example, using non-default labels:
w2 <- wwt; w2$counts <- w2$counts - 1
lines(w2, col = "Midnight Blue", labels = ifelse(w2$counts, "> 1", "1"))
}
\keyword{hplot}
\keyword{iplot}
\eof
\name{plotmath}
\alias{plotmath}
\title{Mathematical Annotation in R}
\description{
  If the \code{text} argument to one of the text-drawing functions
  (\code{\link{text}}, \code{\link{mtext}}, \code{\link{axis}}) in \R
  is an expression, the argument is interpreted as a mathematical
  expression and the output will be formatted according to TeX-like
  rules.  Expressions can also be used for titles, subtitles and
  x- and y-axis labels (but not for axis labels on \code{persp} plots).
}
\details{
  A mathematical expression must obey the normal rules of syntax for any
  \R expression, but it is interpreted according to very different rules
  than for normal \R expressions.

  It is possible to produce many different mathematical symbols, generate
  sub- or superscripts, produce fractions, etc.

  The output from \code{demo(plotmath)} includes several tables which
  show the available features.  In these tables, the columns of grey text
  show sample \R expressions, and the columns of black text show the
  resulting output.

  The available features are also described in the tables below:

  \tabular{ll}{
    \bold{Syntax} \tab \bold{Meaning} \cr
    \code{x + y}   \tab x plus y   \cr
    \code{x - y}   \tab x minus y \cr
    \code{x*y}    \tab juxtapose x and y \cr
    \code{x/y}    \tab x forwardslash y \cr
    \code{x \%+-\% y}   \tab x plus or minus y \cr
    \code{x \%/\% y}   \tab x divided by y \cr
    \code{x \%*\% y}   \tab x times y \cr
    \code{x[i]}   \tab x subscript i \cr
    \code{x^2}    \tab x superscript 2 \cr
    \code{paste(x, y, z)} \tab juxtapose x, y, and z \cr
    \code{sqrt(x)}   \tab square root of x \cr
    \code{sqrt(x, y)}   \tab yth root of x \cr
    \code{x == y}   \tab x equals y \cr
    \code{x != y}   \tab x is not equal to y \cr
    \code{x < y}   \tab x is less than y \cr
    \code{x <= y}   \tab x is less than or equal to y \cr
    \code{x > y}   \tab x is greater than y \cr
    \code{x >= y}   \tab x is greater than or equal to y \cr
    \code{x \%~~\% y}   \tab x is approximately equal to y \cr
    \code{x \%=~\% y}   \tab x and y are congruent \cr
    \code{x \%==\% y}   \tab x is defined as y \cr
    \code{x \%prop\% y}  \tab x is proportional to y \cr
    \code{plain(x)}   \tab draw x in normal font \cr
    \code{bold(x)}   \tab draw x in bold font \cr
    \code{italic(x)}   \tab draw x in italic font \cr
    \code{bolditalic(x)} \tab draw x in bolditalic font \cr
    \code{list(x, y, z)} \tab comma-separated list \cr
    \code{...}    \tab ellipsis (height varies) \cr
    \code{cdots}   \tab ellipsis (vertically centred) \cr
    \code{ldots}   \tab ellipsis (at baseline) \cr
    \code{x \%subset\% y} \tab x is a proper subset of y \cr
    \code{x \%subseteq\% y} \tab x is a subset of y \cr
    \code{x \%notsubset\% y} \tab x is not a subset of y \cr
    \code{x \%supset\% y} \tab x is a proper superset of y \cr
    \code{x \%supseteq\% y} \tab x is a superset of y \cr
    \code{x \%in\% y}   \tab x is an element of y \cr
    \code{x \%notin\% y} \tab x is not an element of y \cr
    \code{hat(x)}   \tab x with a circumflex \cr
    \code{tilde(x)}   \tab x with a tilde \cr
    \code{dot(x)} \tab x with a dot \cr
    \code{ring(x)}   \tab x with a ring \cr
    \code{bar(xy)}   \tab xy with bar \cr
    \code{widehat(xy)}   \tab xy with a wide circumflex \cr
    \code{widetilde(xy)} \tab xy with a wide tilde \cr
    \code{x \%<->\% y}   \tab x double-arrow y \cr
    \code{x \%->\% y}   \tab x right-arrow y \cr
    \code{x \%<-\% y}   \tab x left-arrow y \cr
    \code{x \%up\% y}   \tab x up-arrow y \cr
    \code{x \%down\% y}  \tab x down-arrow y \cr
    \code{x \%<=>\% y}   \tab x is equivalent to y \cr
    \code{x \%=>\% y}   \tab x implies y \cr
    \code{x \%<=\% y}   \tab y implies x \cr
    \code{x \%dblup\% y}   \tab x double-up-arrow y \cr
    \code{x \%dbldown\% y} \tab x double-down-arrow y \cr
    \code{alpha} -- \code{omega} \tab Greek symbols \cr
    \code{Alpha} -- \code{Omega} \tab uppercase Greek symbols \cr
    \code{infinity}   \tab infinity symbol \cr
    \code{partialdiff} \tab partial differential symbol \cr
    \code{32*degree}   \tab 32 degrees \cr
    \code{60*minute}   \tab 60 minutes of angle \cr
    \code{30*second}   \tab 30 seconds of angle \cr
    \code{displaystyle(x)} \tab draw x in normal size (extra spacing) \cr
    \code{textstyle(x)}  \tab draw x in normal size \cr
    \code{scriptstyle(x)} \tab draw x in small size \cr
    \code{scriptscriptstyle(x)} \tab draw x in very small size \cr
    \code{x ~~ y}        \tab put extra space between x and y \cr
    \code{x + phantom(0) + y} \tab leave gap for "0", but don't draw it \cr
    \code{x + over(1, phantom(0))} \tab leave vertical gap for "0" (don't draw) \cr
    \code{frac(x, y)}   \tab x over y \cr
    \code{over(x, y)}   \tab x over y \cr
    \code{atop(x, y)}   \tab x over y (no horizontal bar) \cr
    \code{sum(x[i], i==1, n)} \tab sum x[i] for i equals 1 to n \cr
    \code{prod(plain(P)(X==x), x)} \tab product of P(X=x) for all values of x \cr
    \code{integral(f(x)*dx, a, b)} \tab definite integral of f(x) wrt x \cr
    \code{union(A[i], i==1, n)} \tab union of A[i] for i equals 1 to n \cr
    \code{intersect(A[i], i==1, n)} \tab intersection of A[i] \cr
    \code{lim(f(x), x \%->\% 0)} \tab limit of f(x) as x tends to 0 \cr
    \code{min(g(x), x > 0)} \tab minimum of g(x) for x greater than 0 \cr
    \code{inf(S)}        \tab infimum of S \cr
    \code{sup(S)}   \tab supremum of S \cr
    \code{x^y + z}   \tab normal operator precedence \cr
    \code{x^(y + z)}    \tab visible grouping of operands \cr
    \code{x^{y + z}}  \tab invisible grouping of operands \cr
    \code{group("(",list(a, b),"]")} \tab specify left and right delimiters \cr
    \code{bgroup("(",atop(x,y),")")} \tab use scalable delimiters \cr
    \code{group(lceil, x, rceil)} \tab special delimiters \cr
  }
}
\references{
  Murrell, P. and Ihaka, R. (2000) An approach to providing
  mathematical annotation in plots.
  \emph{Journal of Computational and Graphical Statistics},
  \bold{9}, 582--599.
}
\seealso{
  \code{demo(plotmath)},
  \code{\link{axis}},
  \code{\link{mtext}},
  \code{\link{text}},
  \code{\link{title}},
  \code{\link{substitute}}
  \code{\link{quote}}, \code{\link{bquote}}
}
\examples{
x <- seq(-4, 4, len = 101)
y <- cbind(sin(x), cos(x))
matplot(x, y, type = "l", xaxt = "n",
        main = expression(paste(plain(sin) * phi, "  and  ",
                                plain(cos) * phi)),
        ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
        xlab = expression(paste("Phase Angle ", phi)),
        col.main = "blue")
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
     lab = expression(-pi, -pi/2, 0, pi/2, pi))


## How to combine "math" and numeric variables :
plot(1:10, type="n", xlab="", ylab="", main = "plot math & numbers")
theta <- 1.23 ; mtext(bquote(hat(theta) == .(theta)))
for(i in 2:9)
    text(i,i+1, substitute(list(xi,eta) == group("(",list(x,y),")"),
                           list(x=i, y=i+1)))

plot(1:10, 1:10)
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)",
     cex = .8)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
text(4, 6.4, "expression(bar(x) == sum(frac(x[i], n), i==1, n))",
     cex = .8)
text(8, 5, expression(paste(frac(1, sigma*sqrt(2*pi)), " ",
                            plain(e)^{frac(-(x-mu)^2, 2*sigma^2)})),
     cex = 1.2)
}
\keyword{aplot}
\eof
\name{points}
\alias{points}
\alias{points.default}
\title{Add Points to a Plot}
\description{
  \code{points} is a generic function to draw a sequence of points at
  the specified coordinates.  The specified character(s) are plotted,
  centered at the coordinates.
}
\usage{
points(x, \dots)

\method{points}{default}(x, y = NULL, type = "p", pch = par("pch"),
       col = par("col"), bg = NA, cex = 1, \dots)
}
\arguments{
  \item{x, y}{coordinate vectors of points to plot.}
  \item{type}{character indicating the type of plotting; actually any of
    the \code{type}s as in \code{\link{plot}}.}
  \item{pch}{plotting \dQuote{character}, i.e., symbol to use.  \code{pch} can
    either be a \code{\link{character}} or an integer code for a set of
    graphics symbols.  The full set of S symbols is available with
    \code{pch=0:18}, see the last picture from \code{example(points)},
    i.e., the examples below.
    % (currently, \R uses circles instead of octagons).

    In addition, there is a special set of \R plotting symbols which
    can be obtained with \code{pch=19:25} and \code{21:25} can be
    colored and filled with different colors:
    \itemize{
      \item \code{pch=19}: solid circle,
      \item \code{pch=20}: bullet (smaller circle),
      \item \code{pch=21}: circle,
      \item \code{pch=22}: square,
      \item \code{pch=23}: diamond,
      \item \code{pch=24}: triangle point-up,
      \item \code{pch=25}: triangle point down.
    }
    Values \code{pch=26:32} are currently unused, and \code{pch=32:255}
    give the text symbol in the encoding in use (see \code{\link{postscript}}).
  }
  \item{col}{color code or name, see \code{\link{par}}.}
  \item{bg}{background (\dQuote{fill}) color for open plot symbols}
  \item{cex}{character expansion: a numerical vector.}
  \item{\dots}{Further graphical parameters (see \code{\link{plot.xy}}
    and \code{\link{par}}) may also be supplied as arguments.}
}
\details{
  The coordinates can be passed in a plotting structure
  (a list with \code{x} and \code{y} components), a two-column matrix, a
  time series, \dots.  See \code{\link{xy.coords}}.

  Arguments \code{pch}, \code{col}, \code{bg} and \code{cex} can be
  vectors (which will be recycled as needed) giving a value for each
  point plotted. 
  Points whose \code{x}, \code{y}, \code{pch}, \code{col} or \code{cex}
  value is \code{NA} are omitted from the plot.
  
  Graphical parameters are permitted as arguments to this function.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{plot}}, \code{\link{lines}}, and the underlying
  \dQuote{primitive} \code{\link{plot.xy}}.
}
\examples{
plot(-4:4, -4:4, type = "n")# setting up coord. system
points(rnorm(200), rnorm(200), col = "red")
points(rnorm(100)/2, rnorm(100)/2, col = "blue", cex = 1.5)

op <- par(bg = "light blue")
x <- seq(0,2*pi, len=51)
## something "between type='b' and type='o'":
plot(x, sin(x), type="o", pch=21, bg=par("bg"), col = "blue", cex=.6,
 main='plot(..., type="o", pch=21, bg=par("bg"))')
par(op)

##-------- Showing all the extra & some char graphics symbols ------------
Pex <- 3 ## good for both .Device=="postscript" and "x11"
ipch <- 1:(np <- 25+11); k <- floor(sqrt(np)); dd <- c(-1,1)/2
rx <- dd + range(ix <- (ipch-1) \%/\% k)
ry <- dd + range(iy <- 3 + (k-1)-(ipch-1) \%\% k)
pch <- as.list(ipch)
pch[25+ 1:11] <- as.list(c("*",".", "o","O","0","+","-",":","|","\%","#"))
plot(rx, ry, type="n", axes = FALSE, xlab = "", ylab = "",
     main = paste("plot symbols :  points (...  pch = *, cex =", Pex,")"))
abline(v = ix, h = iy, col = "lightgray", lty = "dotted")
for(i in 1:np) {
  pc <- pch[[i]]
  points(ix[i], iy[i], pch = pc, col = "red", bg = "yellow", cex = Pex)
  ## red symbols with a yellow interior (where available)
  text(ix[i] - .3, iy[i], pc, col = "brown", cex = 1.2)
}
}
\keyword{aplot}
\eof
\name{polygon}
\alias{polygon}
\title{Polygon Drawing}
\description{
  \code{polygon} draws the polygons whose vertices are
  given in \code{x} and \code{y}.
}
\synopsis{
polygon(x, y = NULL, density = NULL, angle = 45,
        border = NULL, col = NA, lty = NULL, xpd = NULL,
        ..debug.hatch = FALSE, \dots)
}
\usage{
polygon(x, y = NULL, density = NULL, angle = 45,
        border = NULL, col = NA, lty = NULL, xpd = NULL, \dots)
}
\arguments{
  \item{x,y}{vectors containing the coordinates of the vertices
    of the polygon.}
  \item{density}{the density of shading lines, in lines per inch.  The
    default value of \code{NULL} means that no shading lines are drawn.
    A zero value of \code{density} means no shading lines whereas
    negative values (and \code{NA}) suppress shading (and so allow
    color filling).}
  \item{angle}{the slope of shading lines, given as an angle
     in degrees (counter-clockwise).}
  \item{col}{the color for filling the polygon.
    The default, \code{NA}, is to leave polygons unfilled.}
  \item{border}{the color to draw the border.  The default, \code{NULL},
    uses \code{\link{par}("fg")}.  Use \code{border = NA} to omit borders.
    
    For compatibility with S, \code{border} can also be logical, in
    which case \code{FALSE} is equivalent to \code{NA} (borders omitted)
    and \code{TRUE} is equivalent to \code{NULL} (use the foreground colour),
  }
  \item{lty}{the line type to be used, as in \code{\link{par}}.}
  \item{xpd}{(where) should clipping take place?  Defaults to
    \code{\link{par}("xpd")}.}
  \item{\dots}{graphical parameters can be given as arguments to
    \code{polygon}.}
}
\details{
  The coordinates can be passed in a plotting structure
  (a list with \code{x} and \code{y} components), a two-column matrix,
  \dots.  See \code{\link{xy.coords}}.

  It is assumed that the polygon is closed by joining the last point to
  the first point.
 
  The coordinates can contain missing values.  The behaviour is similar
  to that of \code{\link{lines}}, except
  that instead of breaking a line into several lines, \code{NA}
  values break the polygon into several complete polygons
  (including closing the last point to the first point).  See
  the examples below.

  When multiple polygons are produced,
  the values of \code{density}, \code{angle}, \code{col}, \code{border},
  and \code{lty} are recycled in the usual manner.
}
\section{Bugs}{
  The present shading algorithm can produce incorrect results for
  self-intersecting polygons.
}
\author{
  The code implementing polygon shading was donated by
  Kevin Buhr \email{buhr@stat.wisc.edu}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{segments}} for even more flexibility, \code{\link{lines}},
  \code{\link{rect}}, \code{\link{box}}, \code{\link{abline}}.

  \code{\link{par}} for how to specify colors.
}
\examples{
x <- c(1:9,8:1)
y <- c(1,2*(5:3),2,-1,17,9,8,2:9)
op <- par(mfcol=c(3,1))
for(xpd in c(FALSE,TRUE,NA)) {
  plot(1:10, main=paste("xpd =", xpd)) ; box("figure", col = "pink", lwd=3)
  polygon(x,y, xpd=xpd, col = "orange", lty=2, lwd=2, border = "red")
}
par(op)

n <- 100
xx <- c(0:n, n:0)
yy <- c(c(0,cumsum(rnorm(n))), rev(c(0,cumsum(rnorm(n)))))
plot   (xx, yy, type="n", xlab="Time", ylab="Distance")
polygon(xx, yy, col="gray", border = "red")
title("Distance Between Brownian Motions")

# Multiple polygons from NA values
# and recycling of col, border, and lty
op <- par(mfrow=c(2,1))
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,1,2,1,2,1),
        col=c("red", "blue"),
        border=c("green", "yellow"),
        lwd=3, lty=c("dashed", "solid"))
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
        col=c("red", "blue"),
        border=c("green", "yellow"),
        lwd=3, lty=c("dashed", "solid"))
par(op)

# Line-shaded polygons
plot(c(1,9), 1:2, type="n")
polygon(1:9, c(2,1,2,1,NA,2,1,2,1),
        density=c(10, 20), angle=c(-45, 45))
}
\keyword{aplot}
\eof
\name{postscript}
\alias{postscript}
\alias{ps.options}
%\alias{.PostScript.Options}
\alias{.ps.prolog}
\concept{encoding}
\title{PostScript Graphics}
\description{
  \code{postscript} starts the graphics device driver for producing
  PostScript graphics.

  The auxiliary function \code{ps.options} can be used to set and view
  (if called without arguments) default values for the arguments to
  \code{postscript}.
}
\synopsis{
postscript(file = ifelse(onefile, "Rplots.ps", "Rplot\%03d.ps"),
           onefile = TRUE, family, title = "R Graphics Output", \dots)
ps.options(\dots, reset = FALSE, override.check = FALSE)
}
%% The definitive doc is the source :-)
%% 	../../../main/devices.c  &   ../../../unix/devPS.c
\usage{
postscript(file = ifelse(onefile, "Rplots.ps", "Rplot\%03d.ps"),
           onefile = TRUE,
           paper, family, encoding, bg, fg,
           width, height, horizontal, pointsize,
           pagecentre, print.it, command, title = "R Graphics Output")

% paper, horizontal, width, height, family, pointsize, bg, fg)
ps.options(paper, horizontal, width, height, family, encoding,
           pointsize, bg, fg,
           onefile = TRUE, print.it = FALSE, append = FALSE,
           reset = FALSE, override.check = FALSE)
}
\arguments{
  \item{file}{a character string giving the name of the file.  If it is
    \code{""}, the output is piped to the command given by
    the argument \code{command}.
#ifdef unix
    If it is \code{"|cmd"}, the output is piped to the command given
    by \file{cmd}.
#endif

    For use with \code{onefile=FALSE} give a \code{printf} format such
    as \code{"Rplot\%03d.ps"} (the default in that case).
  }
%  \item{\dots}{further options for \code{postscript()}.}
  \item{paper}{the size of paper in the printer.  The choices are
    \code{"a4"}, \code{"letter"}, \code{"legal"} and
    \code{"executive"} (and these can be capitalized).
    Also, \code{"special"} can be used, when the \code{width}
    and \code{height} specify the paper size.  A further choice is
    \code{"default"}, which is the default.  If this is selected, the
    papersize is taken from the option \code{"papersize"}
    if that is set and to \code{"a4"} if it is unset or empty.}
  \item{horizontal}{the orientation of the printed image, a
    logical. Defaults to true, that is landscape orientation on paper
    sizes with width less than height.}
  \item{width, height}{the width and height of the graphics region in
    inches.  The default is to use the entire page less a 0.25 inch
    border on each side.}
  \item{family}{the font family to be used.  EITHER a single character
    string OR a character vector of length
    four or five.  See the section \sQuote{Families}.}
  \item{encoding}{the name of an encoding file. Defaults to
#ifdef unix
"ISOLatin1.enc"
#endif
#ifdef windows
"WinAnsi.enc"
#endif
    in the \file{R\_HOME/afm} directory, which is used
    if the path does not contain a path separator.  An extension
    \code{".enc"} can be omitted.}
  \item{pointsize}{the default point size to be used.}
  \item{bg}{the default background color to be used.
    If \code{"transparent"} (or an equivalent specification), no
    background is painted.}
  \item{fg}{the default foreground color to be used.}
  \item{onefile}{logical: if true (the default) allow multiple figures
    in one file.  If false, generate a file name containing the page
    number and use an EPSF header and no \code{DocumentMedia} comment.}
  \item{pagecentre}{logical: should the device region be centred on the
    page: defaults to true.}
  \item{print.it}{logical: should the file be printed when the device is
    closed?  (This only applies if \code{file} is a real file name.)}
  \item{command}{the command to be used for \dQuote{printing}.  Defaults to
    option \code{"printcmd"}; this can also be selected as
    \code{"default"}.}
  \item{append}{logical; currently \bold{disregarded}; just there for
    compatibility reasons.}
  \item{reset, override.check}{logical arguments passed to
    \code{\link{check.options}}.  See the Examples.}
  \item{title}{title string to embed in the file.}
}
\details{
  \code{postscript} opens the file \code{file} and the PostScript
  commands needed to plot any graphics requested are stored in that
  file.  This file can then be printed on a suitable device to obtain
  hard copy.

  A postscript plot can be printed via \code{postscript} in two ways.
  \enumerate{
    \item Setting \code{print.it = TRUE} causes the command given in
    argument \code{command} to be called with argument \code{"file"}
    when the device is closed.
    Note that the plot file is not deleted unless \code{command} arranges to
    delete it.

    \item \code{file=""} or \code{file="|cmd"} can be used to print
    using a pipe on systems that support \file{popen}.  Failure to open the
    command will probably be reported to the terminal but not to
    \file{popen}, in which case close the device by \code{dev.off}
    immediately.
  }
#ifdef windows
  Only the first of these will work on Windows, and the default
  \code{"printcmd"} is empty and will give an error if \code{print.it=TRUE}
  is used.  Suitable commands to spool a PostScript file to a printer
  can be found in \file{RedMon} suite available from
  \url{http://www.cs.wisc.edu/~ghost/index.html}.  The command will be run
  in a minimized window.   GSView 4.x provides
  \file{gsprint.exe} which may be even more convenient (it requires
  GhostScript version 6.0 or later).
#endif

  The postscript produced by \R is EPS (\emph{Encapsulated PostScript})
  compatible, and can be included into other documents, e.g., into
  LaTeX, using \code{\includegraphics{<filename>}}.  For use in this way
  you will probably want to set \code{horizontal = FALSE, onefile = FALSE,
    paper = "special"}.

  Most of the PostScript prologue used is taken from the \R character
  vector \code{.ps.prolog}.  This is marked in the output, and can be
  changed by changing that vector.  (This is only advisable for
  PostScript experts: the standard version is in
  \code{namespace:graphics}.)

  \code{ps.options} needs to be called before calling \code{postscript},
  and the default values it sets can be overridden by supplying
  arguments to \code{postscript}.
}

\section{Families}{
  The argument \code{family} specifies the font family to be used.
  In normal use it is one of \code{"AvantGarde"},
  \code{"Bookman"}, \code{"Courier"}, \code{"Helvetica"},
  \code{"Helvetica-Narrow"}, \code{"NewCenturySchoolbook"},
  \code{"Palatino"} or \code{"Times"}, and refers to the standard
  Adobe PostScript fonts of those names which are included (or cloned)
  in all common PostScript devices.

  Many PostScript emulators (including those based on
  \code{ghostscript}) use the URW equivalents of these fonts, which are
  \code{"URWGothic"}, \code{"URWBookman"}, \code{"NimbusMon"},
  \code{"NimbusSan"}, \code{"NimbusSanCond"}, \code{"CenturySch"},
  \code{"URWPalladio"} and \code{"NimbusRom"} respectively.  If your
  PostScript device is using URW fonts, you will obtain access to more
  characters and more appropriate metrics by using these names.  To make
  these easier to remember, \code{"URWHelvetica" == "NimbusSan"} and
  \code{"URWTimes" == "NimbusRom"} are also supported.

  It is also possible to specify \code{family="ComputerModern"}. This
  is intended to use with the Type 1 versions of the TeX CM fonts.  It
  will normally be possible to include such output in TeX or LaTeX
  provided it is processed with \code{dvips -Ppfb -j0} or the equivalent
  on your system. (\code{-j0} turns off font subsetting.)
  
  If the second form of argument \code{"family"} is used, it should be a
  character vector of four or five paths to Adobe Font Metric files for
  the regular, bold, italic, bold italic and (optionally) symbol fonts to
  be used.  If these paths do not contain the file separator, they are
  taken to refer to files in the \R directory \file{R\_HOME/afm}.  Thus the
  default Helvetica family can be specified by \code{family =
    c("hv______.afm",
    "hvb_____.afm", "hvo_____.afm", "hvbo____.afm", "sy______.afm")}.
  It is the user's responsibility to check that suitable fonts are made
  available, and that they contain the needed characters when
  re-encoded.  The fontnames used are taken from the \code{FontName}
  fields of the afm files.  The software including the PostScript plot
  file should either embed the font outlines (usually from \file{.pfb}
  or \file{.pfa} files) or use DSC comments to instruct the print
  spooler to do so.

  The \code{.afm} files for the first four fonts do not need to be in
  the correct encoding, but that for the symbol font must be.

  When \code{family="ComputerModern"} is used, the italic/bold-italic
  fonts used are slanted fonts (\code{cmsl10} and \code{cmbxsl10}).  To
  use text italic fonts instead, use
  \code{family = c("CM_regular_10.afm", "CM_boldx_10.afm", "cmti10.afm",
    "cmbxti10.afm", "CM_symbol_10.afm")}.
}

\section{Encodings}{
  Encodings describe which glyphs are used to display the character codes
  (in the range 0--255).  By default \R uses ISOLatin1 encoding, and
  the examples for \code{\link{text}} are in that encoding.  However,
  the encoding used on machines running \R may well be different, and by
  using the \code{encoding} argument the glyphs can be matched to
  encoding in use.

  None of this will matter if only ASCII characters (codes 32--126) are
  used as all the encodings agree over that range.  Some encodings are
  supersets of ISOLatin1, too.  However, if accented and special
  characters do not come out as you expect, you may need to change the
  encoding.  Three other encodings are supplied with \R:
  \code{"WinAnsi.enc"} and \code{"MacRoman.enc"} correspond to the
  encodings normally used on Windows and MacOS (at least by Adobe), and
  \code{"PDFDoc.enc"} is the first 256 characters of the Unicode
  encoding, the standard for PDF.

  If you change the encoding, it is your responsibility to ensure that
  the PostScript font contains the glyphs used.  One issue here is the Euro
  symbol which is in the WinAnsi and MacRoman encodings but may well not
  be in the PostScript fonts.  (It is in the URW variants; it is not in
  the supplied Adobe Font Metric files.)

  There is one exception.  Character 45 (\code{"-"}) is always set
  as minus (its value in Adobe ISOLatin1) even though it is hyphen in
  the other encodings.  Hyphen is available as character 173 (octal
  0255) in ISOLatin1.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{Devices}},
  {\code{\link{check.options}} which is called from both
    \code{ps.options} and \code{postscript}}.
}
\author{
  Support for Computer Modern fonts is based on a contribution by
  Brian D'Urso \email{durso@hussle.harvard.edu}.
}
\examples{
\dontrun{
# open the file "foo.ps" for graphics output
postscript("foo.ps")
# produce the desired graph(s)
dev.off()              # turn off the postscript device
#ifdef unix
postscript("|lp -dlw")
# produce the desired graph(s)
dev.off()              # plot will appear on printer
#endif
#ifdef windows
options(printcmd='redpr -P"\\\\markov\\lw"')
postscript(file=tempfile("Rps."), print.it=TRUE)
# produce the desired graph(s)
dev.off()              # send plot file to the printer
#endif

# for URW PostScript devices
postscript("foo.ps", family = "NimbusSan")

## for inclusion in Computer Modern TeX documents, perhaps
postscript("cm_test.eps", width = 4.0, height = 3.0,
           horizontal = FALSE, onefile = FALSE, paper = "special",
           family = "ComputerModern")
## The resultant postscript file can be used by dvips -Ppfb -j0.

## To test out encodings, you can use
TestChars <- function(encoding="ISOLatin1", family="URWHelvetica")
{
    postscript(encoding=encoding, family=family)
    par(pty="s")
    plot(c(0,15), c(0,15), type="n", xlab="", ylab="")
    title(paste("Centred chars in encoding", encoding))
    grid(15, 15, lty=1)
    for(i in c(32:255)) {
	x <- i %% 16
	y <- i %/% 16
	points(x, y, pch=i)
    }
    dev.off()
}
## there will be many warnings. We use URW to get a complete enough
## set of font metrics.
TestChars()
TestChars("ISOLatin2")
TestChars("WinAnsi")
}
\dontshow{
xx <- seq(0, 7, length=701)
yy <- sin(xx)/xx; yy[1] <- 1
plot(xx,yy)                     # produce the desired graph(s)
}

ps.options(bg = "pink")
utils::str(ps.options(reset = TRUE))

### ---- error checking of arguments: ----
ps.options(width=0:12, onefile=0, bg=pi)
# override the check for 'onefile', but not the others:
utils::str(ps.options(width=0:12, onefile=1, bg=pi,
                      override.check = c(FALSE,TRUE,FALSE)))
}
\keyword{device}
\eof
\name{recordPlot}
\alias{replayPlot}
\alias{recordPlot}
\alias{print.recordedplot}
\title{Record and Replay Plots}
\description{
  Functions to save the current plot in an \R variable, and to replay it.
}
\usage{
recordPlot()
replayPlot(x)
}
\arguments{
 \item{x}{A saved plot.}
}
\details{
  These functions record and replay the displaylist of the current
  graphics device.  The returned object is of class
  \code{"recordedplot"}, and \code{replayPlot} acts as a \code{print}
  method for that class.

  The format of recorded plots was changed in \R 1.4.0: plots saved in
  earlier versions can still be replayed.
}
\value{
  \code{recordPlot} returns an object of class \code{"recordedplot"}, a
  list with components:
  \item{displaylist}{The saved display list, as a pairlist.}
  \item{gpar}{The graphics state, as an integer vector.}

  \code{replayPlot} has no return value.
}
\keyword{iplot}
\eof
\name{rect}
\title{Draw One or More Rectangles}
\usage{
rect(xleft, ybottom, xright, ytop, density = NULL, angle = 45,
     col = NULL, border = NULL, lty = NULL, lwd = par("lwd"),
     xpd = NULL, \dots)
}
\alias{rect}
\arguments{
  \item{xleft}{a vector (or scalar) of left x positions.}
  \item{ybottom}{a vector (or scalar) of bottom y positions.}
  \item{xright}{a vector (or scalar) of right x positions.}
  \item{ytop}{a vector (or scalar) of top y positions.}
  \item{density}{the density of shading lines, in lines per inch.
    The default value of \code{NULL} means that no shading lines are drawn.
    A zero value of \code{density} means no shading lines whereas
    negative values (and \code{NA}) suppress shading (and so allow
    color filling).}
  \item{angle}{angle (in degrees) of the shading lines.}
  \item{col}{color(s) to fill or shade the rectangle(s) with.
    The default \code{NULL}, or also \code{\link{NA}} do not fill,
    i.e., draw transparent rectangles, unless \code{density} is specified.}
  \item{border}{color for rectangle border(s). Can also be \code{FALSE}
    to suppress the border, or \code{TRUE} in which case \code{col} is used.}
  \item{lty}{line type for borders and shading; defaults to \code{"solid"}.}
  \item{lwd}{line width for borders and shading.}
  \item{xpd}{logical (\dQuote{e\bold{xp}an\bold{d}}); defaults to
    \code{par("xpd")}.  See \code{\link{par}(xpd= )}.}
  \item{\dots}{other graphical parameters can be given as arguments.}
}
\description{
  \code{rect} draws a rectangle (or sequence of rectangles) with the
  given coordinates, fill and border colors.
}
\details{
  The positions supplied, i.e., \code{xleft, \dots},
  are relative to the current plotting region.  If the x-axis goes from
  100 to 200 then \code{xleft} must be larger than 100 and \code{xright}
  must be less than 200.

  It is a primitive function used in \code{\link{hist}},
  \code{\link{barplot}}, \code{\link{legend}}, etc.
}
\seealso{
  \code{\link{box}} for the \dQuote{standard} box around the plot;
  \code{\link{polygon}} and \code{\link{segments}} for flexible line
  drawing.

  \code{\link{par}} for how to specify colors.
}
\examples{
## set up the plot region:
op <- par(bg = "thistle")
plot(c(100, 250), c(300, 450), type = "n", xlab="", ylab="",
     main = "2 x 11 rectangles; 'rect(100+i,300+i,  150+i,380+i)'")
i <- 4*(0:10)
## draw rectangles with bottom left (100, 300)+i and top right (150, 380)+i
rect(100+i, 300+i, 150+i, 380+i, col=rainbow(11, start=.7,end=.1))
rect(240-i, 320+i, 250-i, 410+i, col=heat.colors(11), lwd=i/5)
## Background alternating  ( transparent / "bg" ) :
j <- 10*(0:5)
rect(125+j, 360+j,   141+j, 405+j/2, col = c(NA,0), border = "gold", lwd = 2)
rect(125+j, 296+j/2, 141+j, 331+j/5, col = c(NA,"midnightblue"))
mtext("+  2 x 6 rect(*, col = c(NA,0)) and  col = c(NA,\"m..blue\"))")

## an example showing colouring and shading
plot(c(100, 200), c(300, 450), type= "n", xlab="", ylab="")
rect(100, 300, 125, 350) # transparent
rect(100, 400, 125, 450, col="green", border="blue") # coloured
rect(115, 375, 150, 425, col=par("bg"), border="transparent")
rect(150, 300, 175, 350, density=10, border="red")
rect(150, 400, 175, 450, density=30, col="blue",
     angle=-30, border="transparent")

legend(180, 450, legend=1:4, fill=c(NA, "green", par("fg"), "blue"),
       density=c(NA, NA, 10, 30), angle=c(NA, NA, 30, -30))

par(op)
}
\keyword{aplot}
\eof
\name{rgb}
\title{RGB Color Specification}
\usage{
rgb(red, green, blue, names=NULL, maxColorValue = 1)
}
\alias{rgb}
\description{
  This function creates \dQuote{colors} corresponding to the given
  intensities (between 0 and \code{max}) of the red, green and blue
  primaries.  The names argument may be used to provide names for the
  colors.

  The values returned by \code{rgb} can be used with a
  \code{col=} specification in graphics functions or in \code{\link{par}}.
}
\arguments{
  \item{red, blue, green}{vectors of same length with values in \eqn{[0, M]}
    where \eqn{M} is \code{maxColorValue}. When this is \code{255}, the
    \code{red}, \code{blue} and \code{green} values are coerced to
    integers in \code{0:255} and the result is computed most efficiently.}
  \item{names}{character. The names for the resulting vector.}
  \item{maxColorValue}{number giving the maximum of the color values
    range, see above.}
}
\seealso{
  \code{\link{col2rgb}} the \dQuote{inverse} for translating \R colors
  to RGB vectors;
  \code{\link{rainbow}}, \code{\link{hsv}}, \code{\link{gray}}.
}
\examples{
rgb(0,1,0)
(u01 <- seq(0,1, length=11))
stopifnot(rgb(u01,u01,u01) == gray(u01))
reds <- rgb((0:15)/15, g=0,b=0, names=paste("red",0:15,sep="."))
reds

rgb(0, 0:12, 0, max = 255)# integer input
}
\keyword{color}
\eof
\name{rgb2hsv}
\alias{rgb2hsv}
\title{RGB to HSV Conversion}
\concept{color space conversion}
\description{
  \code{rgb2hsv} transforms colors
  from RGB space (red/green/blue)
  into HSV space (hue/saturation/value).
}
\usage{
rgb2hsv(r, g = NULL, b = NULL, gamma = 1, maxColorValue = 255)
}
\arguments{
  \item{r}{vector of \dQuote{red} values in \eqn{[0,M]}, (\eqn{M
      =}\code{maxColorValue}) or 3-row rgb matrix.}
  \item{g}{vector of \dQuote{green} values, or \code{\link{NULL}} when
    \code{r} is a matrix.}
  \item{b}{vector of \dQuote{blue} values, or \code{\link{NULL}} when
    \code{r} is a matrix.}
  \item{gamma}{a \dQuote{gamma correction} (supposedly applied to the
    r,g,b values previously), see \code{\link{hsv}(...., gamma)}.}
  \item{maxColorValue}{number giving the maximum of the RGB color values
    range.  The default \code{255} corresponds to the typical \code{0:255}
    RGB coding as in \code{\link{col2rgb}()}.}
}
\details{
 Value (brightness) gives the amount of light in the color.\cr
 Hue describes the dominant wavelegth.\cr
 Saturation is the amount of Hue mixed into the color.
}
\value{
  A matrix with a column for each color.  The three rows of the matrix
  indicate hue, saturation and value and are named \code{"h"},
  \code{"s"}, and \code{"v"} accordingly.
}
\seealso{
  \code{\link{hsv}}, \code{\link{col2rgb}}, \code{\link{rgb}}.
}
\author{
  \R interface by Wolfram Fischer \email{wolfram@fischer-zim.ch};\cr
  C code mainly by Nicholas Lewin-Koh \email{nikko@hailmail.net}.
}
\examples{
## These (saturated, bright ones) only differ by hue
(rc <- col2rgb(c("red", "yellow","green","cyan", "blue", "magenta")))
(hc <- rgb2hsv(rc))
6 * hc["h",] # the hues are equispaced

\testonly{set.seed(151)}
(rgb3 <- floor(256 * matrix(runif(3*12), 3,12)))
(hsv3 <- rgb2hsv(rgb3))
## Consistency :
stopifnot(rgb3 == col2rgb(hsv(h=hsv3[1,], s=hsv3[2,], v=hsv3[3,])),
          all.equal(hsv3, rgb2hsv(rgb3/255, maxC = 1)))

## A (simplified) pure R version -- originally by Wolfram Fischer --
## showing the exact algorithm:
rgb2hsvR <- function(rgb, gamma = 1, maxColorValue = 255)
{
    if(!is.numeric(rgb)) stop("rgb matrix must be numeric")
    d <- dim(rgb)
    if(d[1] != 3) stop("rgb matrix must have 3 rows")
    n <- d[2]
    if(n == 0) return(cbind(c(h=1,s=1,v=1))[,0])
    rgb <- rgb/maxColorValue
    if(gamma != 1) rgb <- rgb ^ (1/gamma)

    ## get the max and min
    v <- apply( rgb, 2, max)
    s <- apply( rgb, 2, min)
    D <- v - s # range

    ## set hue to zero for undefined values (gray has no hue)
    h <- numeric(n)
    notgray <- ( s != v )

    ## blue hue
    idx <- (v == rgb[3,] & notgray )
    if (any (idx))
	h[idx] <- 2/3 + 1/6 * (rgb[1,idx] - rgb[2,idx]) / D[idx]
    ## green hue
    idx <- (v == rgb[2,] & notgray )
    if (any (idx))
	h[idx] <- 1/3 + 1/6 * (rgb[3,idx] - rgb[1,idx]) / D[idx]
    ## red hue
    idx <- (v == rgb[1,] & notgray )
    if (any (idx))
	h[idx] <-	1/6 * (rgb[2,idx] - rgb[3,idx]) / D[idx]

    ## correct for negative red
    idx <- (h < 0)
    h[idx] <- 1+h[idx]

    ## set the saturation
    s[! notgray] <- 0;
    s[notgray] <- 1 - s[notgray] / v[notgray]

    rbind( h=h, s=s, v=v )
}

## confirm the equivalence:
all.equal(rgb2hsv (rgb3),
          rgb2hsvR(rgb3), tol=1e-14) # TRUE
}
\keyword{color}
\keyword{dplot}
\eof
\name{rug}
\title{Add a Rug to a Plot}
\alias{rug}
\usage{
rug(x, ticksize=0.03, side=1, lwd=0.5, col,
    quiet = getOption("warn") < 0, \dots)
}
\arguments{
 \item{x}{A numeric vector}
 \item{ticksize}{The length of the ticks making up the \sQuote{rug}.
   Positive lengths give inwards ticks.}
 \item{side}{On which side of the plot box the rug will be
   plotted. Normally 1 (bottom) or 3 (top).}
 \item{lwd}{The line width of the ticks.}
 \item{col}{The colour the ticks are plotted in, default is black.}
 \item{quiet}{logical indicating if there should be a warning about
   clipped values.}
 \item{\dots}{further arguments, passed to \code{\link{axis}(...)}, such
   as \code{line} or \code{pos} for specifying the location of the rug.}
}
\description{
  Adds a \emph{rug} representation (1-d plot) of the data to the plot.
}
\details{
  Because of the way \code{rug} is implemented, only values of \code{x}
  that fall within the plot region are included.  There will be a
  warning if any finite values are omitted, but non-finite values are
  omitted silently.

  Because of the way colours are done the axis itself is coloured the
  same as the ticks.  You can always replot the box in black if you don't
  like this feature.
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S.}
  Wadsworth \& Brooks/Cole.
}
\seealso{\code{\link{jitter}} which you may want for ties in \code{x}.}
\examples{
data(faithful)
with(faithful, {
    plot(stats::density(eruptions, bw=0.15))
    rug(eruptions)
    rug(jitter(eruptions, amount = .01), side = 3, col = "light blue")
})
}
\keyword{aplot}
\eof
\name{screen}
\title{Creating and Controlling Multiple Screens on a Single Device}
\usage{
split.screen(figs, screen, erase = TRUE)
screen(n = , new = TRUE)
erase.screen(n = )
close.screen(n, all.screens = FALSE)
}
\alias{screen}
\alias{split.screen}
\alias{erase.screen}
\alias{close.screen}
\arguments{
  \item{figs}{A two-element vector describing the number of rows and the
    number of columns in a screen matrix \emph{or} a matrix with 4 columns.
    If a matrix, then each row describes a screen with values for the left,
    right, bottom, and top of the screen (in that order) in NDC units,
    that is 0 at the lower left coner of the device surface, and 1 at
    the upper right corner.}
  \item{screen}{A number giving the screen to be split.  It defaults to
    the current screen if there is one, otherwise the whole device region.}
  \item{erase}{logical: should be selected screen be cleared?}
  \item{n}{A number indicating which screen to prepare for drawing
    (\code{screen}), erase (\code{erase.screen}), or close
    (\code{close.screen}).  (\code{close.screen} will accept a vector of
    screen numbers.)}
  \item{new}{A logical value indicating whether the screen should be
    erased as part of the preparation for drawing in the screen.}
  \item{all.screens}{A logical value indicating whether all of the
    screens should be closed.}
}
\description{
  \code{split.screen} defines a number of regions within the current
  device which can, to some extent, be treated as separate graphics
  devices.  It is useful for generating multiple plots on a single
  device.  Screens can themselves be split, allowing for quite complex
  arrangements of plots.

  \code{screen} is used to select which screen to draw in.

  \code{erase.screen} is used to clear a single screen, which it
  does by filling with the background colour.

  \code{close.screen} removes the specified screen definition(s).
}
\details{
  The first call to \code{split.screen} places \R into split-screen
  mode.  The other split-screen functions only work within this mode.
  While in this mode, certain other commands should be avoided (see the
  Warnings section below).  Split-screen mode is exited by the command
  \code{close.screen(all = TRUE)}.

  If the current screen is closed, \code{close.screen} sets the current
  screen to be the next larger screen number if there is one, otherwise
  to the first available screen.
}
\value{
  \code{split.screen} returns a vector of screen numbers for the
  newly-created screens.  With no arguments, \code{split.screen} returns
  a vector of valid screen numbers.

  \code{screen} invisibly returns the number of the selected screen.
  With no arguments, \code{screen} returns the number of the current
  screen.

  \code{close.screen} returns a vector of valid screen numbers.

  \code{screen}, \code{erase.screen}, and \code{close.screen} all return
  \code{FALSE} if \R is not in split-screen mode.
}

\section{Warnings}{
  The recommended way to use these functions is to completely draw a
  plot and all additions (ie. points and lines) to the base plot, prior to
  selecting and plotting on another screen. The behavior associated with
  returning to a screen to add to an existing plot is unpredictable and
  may result in problems that are not readily visible.

  These functions are totally incompatible with the other mechanisms for
  arranging plots on a device: \code{\link{par}(mfrow)},
  \code{par(mfcol)} and \code{\link{layout}()}.

  The functions are also incompatible with some plotting functions,
  such as \code{\link{coplot}}, which make use of these other mechanisms.

  \code{erase.screen} will appear not to work if the background colour
  is transparent (as it is by default on most devices).
}

\seealso{
  \code{\link{par}}, \code{\link{layout}}, \code{\link{Devices}},
  \code{dev.*}
}
\references{
  Chambers, J. M. and Hastie, T. J. (1992)
  \emph{Statistical Models in S}.
  Wadsworth \& Brooks/Cole.
}

\examples{
if (interactive()) {
par(bg = "white")           # default is likely to be transparent
split.screen(c(2,1))        # split display into two screens
split.screen(c(1,3), screen = 2) # now split the bottom half into 3
screen(1) # prepare screen 1 for output
plot(10:1)
screen(4) # prepare screen 4 for output
plot(10:1)
close.screen(all = TRUE)    # exit split-screen mode

split.screen(c(2,1))        # split display into two screens
split.screen(c(1,2),2)      # split bottom half in two
plot(1:10)                  # screen 3 is active, draw plot
erase.screen()              # forgot label, erase and redraw
plot(1:10, ylab= "ylab 3")
screen(1)                   # prepare screen 1 for output
plot(1:10)
screen(4)                   # prepare screen 4 for output
plot(1:10, ylab="ylab 4")
screen(1, FALSE)            # return to screen 1, but do not clear
plot(10:1, axes=FALSE, lty=2, ylab="")  # overlay second plot
axis(4)                     # add tic marks to right-hand axis
title("Plot 1")
close.screen(all = TRUE)    # exit split-screen mode
}
}
\keyword{aplot}
\keyword{dplot}
\keyword{device}
\eof
\name{segments}
\alias{segments}
\title{Add Line Segments to a Plot}
\description{
  Draw line segments between pairs of points.
}
\usage{
segments(x0, y0, x1, y1,
       col = par("fg"), lty = par("lty"), lwd = par("lwd"), \dots)
}
\arguments{
  \item{x0,y0}{coordinates of points \bold{from} which to draw.}
  \item{x1,y1}{coordinates of points \bold{to} which to draw.}
  \item{col, lty, lwd}{usual graphical parameters as in
    \code{\link{par}}.}
  \item{\dots}{further graphical parameters (from \code{\link{par}}).}
}
\details{
  For each \code{i}, a line segment is drawn between the point
  \code{(x0[i], y0[i])} and the point \code{(x1[i],y1[i])}.

  The graphical parameters \code{col} and \code{lty} can be used to
  specify a color and line texture for the line segments (\code{col}
  may be a vector).
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{arrows}}, 
  \code{\link{polygon}} for slightly easier and less flexible line
  drawing, and
  \code{\link{lines}} for the usual polygons.
}
\examples{
x <- runif(12); y <- rnorm(12)
i <- order(x,y); x <- x[i]; y <- y[i]
plot(x,y, main="arrows(.) and segments(.)")
## draw arrows from point to point :
s <- seq(length(x)-1)# one shorter than data
arrows(x[s], y[s], x[s+1], y[s+1], col= 1:3)
s <- s[-length(s)]
segments(x[s], y[s], x[s+2], y[s+2], col= 'pink')
}
\keyword{aplot}
\eof
\name{stars}
\alias{stars}
\title{Star (Spider/Radar) Plots and Segment Diagrams}
\description{
  Draw star plots or segment diagrams of a multivariate data set.
  With one single location, also draws \dQuote{spider} (or \dQuote{radar}) plots.
}
\usage{
stars(x, full = TRUE, scale = TRUE, radius = TRUE,
      labels = dimnames(x)[[1]], locations = NULL,
      nrow = NULL, ncol = NULL, len = 1,
      key.loc = NULL, key.labels = dimnames(x)[[2]], key.xpd = TRUE,
      xlim = NULL, ylim = NULL, flip.labels = NULL,
      draw.segments = FALSE, col.segments = 1:n.seg, col.stars = NA,
      axes = FALSE, frame.plot = axes,
      main = NULL, sub = NULL, xlab = "", ylab = "",
      cex = 0.8, lwd = 0.25, lty = par("lty"), xpd = FALSE,
      mar = pmin(par("mar"),
                 1.1+ c(2*axes+ (xlab != ""), 2*axes+ (ylab != ""), 1,0)),
      add=FALSE, plot=TRUE, \dots)
}
\arguments{
  \item{x}{matrix or data frame of data.
    One star or segment plot will be produced for each row of \code{x}.
    Missing values (\code{NA}) are allowed, but they are treated as if
    they were 0 (after scaling, if relevant).}
  \item{full}{logical flag: if \code{TRUE}, the segment plots will
    occupy a full circle.  Otherwise, they occupy the (upper) semicircle
    only.}
  \item{scale}{logical flag: if \code{TRUE}, the columns of the data
    matrix are scaled independently so that the maximum value in each
    column is 1 and the minimum is 0.  If \code{FALSE}, the presumption
    is that the data have been scaled by some other algorithm to the
    range \eqn{[0,1]}.}
  \item{radius}{logical flag: in \code{TRUE}, the radii corresponding to
    each variable in the data will be drawn.}
  \item{labels}{vector of character strings for labeling the plots.
    Unlike the S function \code{stars}, no attempt is made to construct
    labels if \code{labels = NULL}.}
  \item{locations}{Either two column matrix with the x and y coordinates used
    to place each of the segment plots; or numeric of length 2 when all
    plots should be superimposed (for a \dQuote{spider plot}).
    By default, \code{locations = NULL}, the segment plots will be
    placed in a rectangular grid.}
  \item{nrow, ncol}{integers giving the number of rows and columns to use when
    \code{locations} is \code{NULL}.  By default, \code{nrow == ncol}, a square
    layout will be used.}
  \item{len}{scale factor for the length of radii or segments.}
  \item{key.loc}{vector with x and y coordinates of the unit key.}
  \item{key.labels}{vector of character strings for labeling the
    segments of the unit key.  If omitted, the second component of
    \code{dimnames(x)} is used, if available.}
  \item{key.xpd}{clipping switch for the unit key (drawing and
    labeling), see \code{\link{par}("xpd")}.}
  \item{xlim}{vector with the range of x coordinates to plot. }
  \item{ylim}{vector with the range of y coordinates to plot.}
  \item{flip.labels}{logical indicating if the label locations should
    flip up and down from diagram to diagram. Defaults to a somewhat
    smart heuristic.}
  \item{draw.segments}{logical. If \code{TRUE} draw a segment diagram.}
  \item{col.segments}{color vector (integer or character, see
    \code{\link{par}}), each specifying a color for one of the segments
    (variables).  Ignored if \code{draw.segments = FALSE}.}
  \item{col.stars}{color vector (integer or character, see
    \code{\link{par}}), each specifying a color for one of the stars
    (cases).  Ignored if \code{draw.segments = TRUE}.}
  \item{axes}{logical flag: if \code{TRUE} axes are added to the plot.}
  \item{frame.plot}{logical flag: if \code{TRUE}, the plot region is framed.}
  \item{main}{a main title for the plot.}
  \item{sub}{a sub title for the plot.}
  \item{xlab}{a label for the x axis.}
  \item{ylab}{a label for the y axis.}
  \item{cex}{character expansion factor for the labels.}
  \item{lwd}{line width used for drawing.}
  \item{lty}{line type used for drawing.}
  \item{xpd}{logical or NA indicating if clipping should be done, see
    \code{\link{par}(xpd = .)}.}
  \item{mar}{argument to \code{\link{par}(mar = *)}, typically choosing
    smaller margings than by default.}
  \item{\dots}{further arguments, passed to the first call of
    \code{plot()}, see \code{\link{plot.default}} and to
    \code{\link{box}()} if \code{frame.plot} is true.}
  \item{add}{logical, if \code{TRUE} \emph{add} stars to current plot.}
  \item{plot}{logical, if \code{FALSE}, nothing is plotted.}
}
\details{
  Missing values are treated as 0.

  Each star plot or segment diagram represents one row of the input
  \code{x}.  Variables (columns) start on the right and wind
  counterclockwise around the circle.  The size of the (scaled) column
  is shown by the distance from the center to the point on the star or
  the radius of the segment representing the variable.

  Only one page of output is produced.
}
\author{Thomas S. Dye}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\note{
  This code started life as spatial star plots by David A. Andrews.
  See \url{http://www.udallas.edu:8080/~andrews/software/software.html}.

  Prior to 1.4.1, scaling only shifted the maximum to 1, although
  documented as here.
}
\examples{
data(mtcars)
stars(mtcars[, 1:7], key.loc = c(14, 2),
      main = "Motor Trend Cars : stars(*, full = F)", full = FALSE)
stars(mtcars[, 1:7], key.loc = c(14, 1.5),
      main = "Motor Trend Cars : full stars()",flip.labels=FALSE)

## 'Spider' or 'Radar' plot:
stars(mtcars[, 1:7], locations = c(0,0), radius = FALSE,
      key.loc=c(0,0), main="Motor Trend Cars", lty = 2)

## Segment Diagrams:
palette(rainbow(12, s = 0.6, v = 0.75))
stars(mtcars[, 1:7], len = 0.8, key.loc = c(12, 1.5),
      main = "Motor Trend Cars", draw.segments = TRUE)
stars(mtcars[, 1:7], len = 0.6, key.loc = c(1.5, 0),
      main = "Motor Trend Cars", draw.segments = TRUE,
      frame.plot=TRUE, nrow = 4, cex = .7)

data(USJudgeRatings)
## scale linearly (not affinely) to [0, 1]
USJudge <- apply(USJudgeRatings, 2, function(x) x/max(x))
Jnam <- row.names(USJudgeRatings)
Snam <- abbreviate(substring(Jnam,1,regexpr("[,.]",Jnam) - 1), 7)
stars(USJudge, labels = Jnam, scale = FALSE,
      key.loc = c(13, 1.5), main = "Judge not ...", len = 0.8)
stars(USJudge, labels = Snam, scale = FALSE,
      key.loc = c(13, 1.5), radius = FALSE)

loc <- stars(USJudge, labels = NULL, scale = FALSE,
             radius = FALSE, frame.plot = TRUE,
             key.loc = c(13, 1.5), main = "Judge not ...", len = 1.2)
text(loc, Snam, col = "blue", cex = 0.8, xpd = TRUE)

## 'Segments':
stars(USJudge, draw.segments = TRUE, scale = FALSE, key.loc = c(13,1.5))

## 'Spider':
stars(USJudgeRatings, locations=c(0,0), scale=FALSE,radius = FALSE,
      col.stars=1:10, key.loc = c(0,0), main="US Judges rated")
## 'Radar-Segments'
stars(USJudgeRatings[1:10,], locations = 0:1, scale=FALSE,
      draw.segments = TRUE, col.segments=0, col.stars=1:10,key.loc= 0:1,
       main="US Judges 1-10 ")
palette("default")
stars(cbind(1:16,10*(16:1)),draw.segments=TRUE,
      main = "A Joke -- do *not* use symbols on 2D data!")
}
\keyword{hplot}
\keyword{multivariate}
\eof
\name{stem}
\title{Stem-and-Leaf Plots}
\usage{
stem(x, scale = 1, width = 80, atom = 1e-08)
}
\alias{stem}
\description{
  \code{stem} produces a stem-and-leaf plot of the values in \code{x}.
  The parameter \code{scale} can be used to expand the scale of the
  plot.  A value of \code{scale=2} will cause the plot to be roughly
  twice as long as the default.
}
\arguments{
  \item{x}{a numeric vector.}
  \item{scale}{This controls the plot length.}
  \item{width}{The desired width of plot.}
  \item{atom}{a tolerance.}
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\examples{
data(islands)
stem(islands)
stem(log10(islands))
}
\keyword{univar}
\keyword{distribution}
\eof
\name{stripchart}
\title{1-D Scatter Plots}
\alias{stripchart}
\description{
  \code{stripchart} produces one dimensional scatter plots (or dot
  plots) of the given data.  These plots are a good alternative to
  \code{\link{boxplot}}s when sample sizes are small.
}
\usage{
stripchart(x, method="overplot", jitter=0.1, offset=1/3,
           vertical=FALSE, group.names, add = FALSE, at = NULL,
           xlim=NULL, ylim=NULL, main="", ylab="", xlab="",
           log="", pch=0, col=par("fg"), cex=par("cex"))
}
\arguments{
  \item{x}{the data from which the plots are to be produced.  The data
    can be specified as a single vector, or as list of vectors, each
    corresponding to a component plot.  Alternatively a symbolic
    specification of the form \code{x ~ g} can be given, indicating the
    the observations in the vector \code{x} are to be grouped according
    to the levels of the factor \code{g}.
    \code{NA}s are allowed in the data.}
  \item{method}{the method to be used to separate coincident points.
    The default method \code{"overplot"} causes such points to be
    overplotted, but it is also possible to specify \code{"jitter"} to
    jitter the points, or \code{"stack"} have coincident points
    stacked.  The last method only makes sense for very granular data.}
  \item{jitter}{when jittering is used, \code{jitter} gives the amount
    of jittering applied.}
  \item{offset}{when stacking is used, points are stacked this many
    line-heights (symbol widths) apart.}
  \item{vertical}{when vertical is \code{TRUE} the plots are drawn
    vertically rather than the default horizontal.}
  \item{group.names}{group labels which will be printed alongside
    (or underneath) each plot.}
  \item{add}{logical, if true \emph{add} boxplot to current plot.}
  \item{at}{numeric vector giving the locations where the boxplots should
    be drawn, particularly when \code{add = TRUE};
    defaults to \code{1:n} where \code{n} is the number of boxes.}
  \item{xlim, ylim, main, ylab, xlab, log, pch, col, cex}{Graphical parameters.}
}
\details{
  Extensive examples of the use of this kind of plot can be found in
  Box, Hunter and Hunter or Seber and Wild.
}
\examples{
x <- rnorm(50)
xr <- round(x, 1)
stripchart(x) ; m <- mean(par("usr")[1:2])
text(m, 1.04, "stripchart(x, \"overplot\")")
stripchart(xr, method = "stack", add = TRUE, at = 1.2)
text(m, 1.35, "stripchart(round(x,1), \"stack\")")
stripchart(xr, method = "jitter", add = TRUE, at = 0.7)
text(m, 0.85, "stripchart(round(x,1), \"jitter\")")

data(OrchardSprays)
with(OrchardSprays,
     stripchart(decrease ~ treatment,
                main = "stripchart(Orchardsprays)", ylab = "decrease",
                vertical = TRUE, log = "y"))
% Fixme: ylab should have a non-""  default !

with(OrchardSprays,
     stripchart(decrease ~ treatment, at = c(1:8)^2,
                main = "stripchart(Orchardsprays)", ylab = "decrease",
                vertical = TRUE, log = "y"))
}
\keyword{hplot}
\eof
\name{strwidth}
\title{Plotting Dimensions of Character Strings and Math Expressions}
\usage{
strwidth(s, units = "user", cex = NULL)
strheight(s, units = "user", cex = NULL)
}
\alias{strwidth}
\alias{strheight}
\arguments{
  \item{s}{character vector or \code{\link{expression}}s whose string
    widths in plotting units are to be determined.  An attempt is made
    to coerce other vectors to character, and other language objects
    to expressions.}
  \item{units}{character indicating in which units \code{s} is measured;
    should be one of \code{"user"}, \code{"inches"}, \code{"figure"};
    partial matching is performed.}
  \item{cex}{character expansion to which is applies.  By default, the
    current \code{par("cex")} is used.}
}
\description{
  These functions compute the width or height, respectively, of the
  given strings or mathematical expressions \code{s[i]} on
  the current plotting device in \emph{user} coordinates, \emph{inches}
  or as fraction of the figure width \code{par("fin")}.
}
\value{
  Numeric vector with the same length as \code{s}, giving the
  width or height for each \code{s[i]}.  \code{NA} strings are given
  width and height 0 (as they are not plotted).
}
\seealso{
  \code{\link{text}}, \code{\link{nchar}}
}
\examples{
str.ex <- c("W","w","I",".","WwI.")
op <- par(pty='s'); plot(1:100,1:100, type="n")
sw <- strwidth(str.ex); sw
all.equal(sum(sw[1:4]), sw[5])#- since the last string contains the others

sw.i <- strwidth(str.ex, "inches"); 25.4 * sw.i # width in [mm]
unique(sw / sw.i)
# constant factor: 1 value
mean(sw.i / strwidth(str.ex, "fig")) / par('fin')[1] # = 1: are the same

## See how letters fall in classes -- depending on graphics device and font!
all.lett <- c(letters, LETTERS)
shL <- strheight(all.lett, units = "inches") * 72 # 'big points'
table(shL) # all have same heights ...
mean(shL)/par("cin")[2] # around 0.6

(swL <- strwidth(all.lett, units="inches") * 72) # 'big points'
split(all.lett, factor(round(swL, 2)))

sumex <- expression(sum(x[i], i=1,n), e^{i * pi} == -1)
strwidth(sumex)
strheight(sumex)

par(op)#- reset to previous setting
}
\keyword{dplot}
\keyword{character}
\eof
\name{sunflowerplot}
\alias{sunflowerplot}
\title{Produce a Sunflower Scatter Plot}
\description{
  Multiple points are plotted as \dQuote{sunflowers} with multiple leaves
  (\dQuote{petals}) such that overplotting is visualized instead of accidental and
  invisible.
}
\usage{
sunflowerplot(x, y = NULL, number, log = "", digits = 6,
             xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
             add = FALSE, rotate = FALSE,
             pch = 16, cex = 0.8, cex.fact = 1.5,
             size = 1/8, seg.col = 2, seg.lwd = 1.5, \dots)
}
\arguments{
  \item{x}{numeric vector of \code{x}-coordinates of length \code{n},
    say, or another valid plotting structure, as for
    \code{\link{plot.default}}, see also \code{\link{xy.coords}}.}
  \item{y}{numeric vector of \code{y}-coordinates of length \code{n}.}
  \item{number}{integer vector of length \code{n}. \code{number[i]} = number
    of replicates for \code{(x[i],y[i])}, may be 0.\cr
    Default: compute the exact multiplicity of the points \code{x[],y[]}.}
  \item{log}{character indicating log coordinate scale, see
    \code{\link{plot.default}}.}
  \item{digits}{when \code{number} is computed (i.e., not specified),
    \code{x} and \code{y} are rounded to \code{digits} significant
    digits before multiplicities are computed.}
  \item{xlab,ylab}{character label for x-, or y-axis, respectively.}
  \item{xlim,ylim}{\code{numeric(2)} limiting the extents of the x-,
    or y-axis.}
  \item{add}{logical; should the plot be added on a previous one ?
    Default is \code{FALSE}.}
  \item{rotate}{logical; if \code{TRUE}, randomly rotate the
    sunflowers (preventing artefacts).}
  \item{pch}{plotting character to be used for points
    (\code{number[i]==1}) and center of sunflowers.}
  \item{cex}{numeric; character size expansion of center points
    (s. \code{pch}).}
  \item{cex.fact}{numeric \emph{shrinking} factor to be used for the
    center points \emph{when there are flower leaves},
    i.e., \code{cex / cex.fact} is used for these.}
  \item{size}{of sunflower leaves in inches, 1[in] := 2.54[cm].
    Default: 1/8\", approximately 3.2mm.}
  \item{seg.col}{color to be used for the \bold{seg}ments which make the
    sunflowers leaves, see \code{\link{par}(col=)};
    \code{col = "gold"} reminds of real sunflowers.}
  \item{seg.lwd}{numeric; the line width for the leaves' segments.}
  \item{\dots}{further arguments to \code{\link{plot}} [if
    \code{add=FALSE}].}
}
\details{
  For \code{number[i]==1}, a (slightly enlarged) usual plotting symbol
  (\code{pch}) is drawn.
  For \code{number[i] > 1}, a small plotting symbol is drawn and
  \code{number[i]} equi-angular \dQuote{rays} emanate from it.

  If \code{rotate=TRUE} and \code{number[i] >= 2}, a random direction
  is chosen (instead of the y-axis) for the first ray.  The goal is to
  \code{\link{jitter}} the orientations of the sunflowers in order to prevent
  artefactual visual impressions.
}
\section{Side Effects}{
  A scatter plot is drawn with \dQuote{sunflowers} as symbols.
}
\value{
  A list with three components of same length,
  \item{x}{x coordinates}
  \item{y}{y coordinates}
  \item{number}{number}
}
\references{
  Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983)
  \emph{Graphical Methods for Data Analysis.}  Wadsworth.

  Schilling, M. F. and Watkins, A. E. (1994)
  A suggestion for sunflower plots.
  \emph{The American Statistician}, \bold{48}, 303--305.
}
\author{
  Andreas Ruckstuhl, Werner Stahel, Martin Maechler, Tim Hesterberg,
  1989--1993.  Port to \R by Martin Maechler
  \email{maechler@stat.math.ethz.ch}.
}
\seealso{\code{\link[stats]{density}}}
\examples{
data(iris)
## 'number' is computed automatically:
sunflowerplot(iris[, 3:4])
## Imitating  Chambers et al., p.109, closely:
sunflowerplot(iris[, 3:4],cex=.2, cex.f=1, size=.035, seg.lwd=.8)

sunflowerplot(x=sort(2*round(rnorm(100))), y= round(rnorm(100),0),
             main = "Sunflower Plot of Rounded N(0,1)")

## A 'point process' {explicit 'number' argument}:
sunflowerplot(rnorm(100),rnorm(100), number=rpois(n=100,lambda=2),
                        rotate=TRUE, main="Sunflower plot")
}
\keyword{hplot}
\keyword{smooth}
\keyword{nonparametric}
\eof
\name{symbols}
\alias{symbols}
\title{Draw symbols on a plot}
\description{
  This function draws symbols on a plot.  One of six symbols;
  \emph{circles}, \emph{squares}, \emph{rectangles}, \emph{stars},
  \emph{thermometers}, and \emph{boxplots}, can be plotted at a
  specified set of x and y coordinates.  Specific aspects of the
  symbols, such as relative size, can be customized by additional
  parameters.
}
\usage{
symbols(x, y = NULL, circles, squares, rectangles, stars,
        thermometers, boxplots, inches = TRUE, add = FALSE,
        fg = 1, bg = NA, xlab = NULL, ylab = NULL, main = NULL,
        xlim = NULL, ylim = NULL, \dots)
}
\arguments{
  \item{x, y}{the x and y co-ordinates for the symbols. They can be
    specified in any way which is accepted by \code{\link{xy.coords}}.}
  \item{circles}{a vector giving the radii of the circles.}
  \item{squares}{a vector giving the length of the sides of the squares.}
  \item{rectangles}{a matrix with two columns.  The first column gives
    widths and the second the heights of rectangle symbols.}
  \item{stars}{a matrix with three or more columns giving the lengths
    of the rays from the center of the stars.  \code{NA} values
    are replaced by zeroes.}
  \item{thermometers}{a matrix with three or four columns.  The first
    two columns give the width and height of the thermometer symbols.
    If there are three columns, the third is taken as a proportion.
    The thermometers are filled from their base to this proportion
    of their height.  If there are four columns, the third and fourth
    columns are taken as proportions.  The thermometers are filled
    between these two proportions of their heights.}
  \item{boxplots}{a matrix with five columns.  The first two columns
    give the width and height of the boxes, the next two columns
    give the lengths of the lower and upper whiskers and the fifth
    the proportion (with a warning if not in [0,1]) of the way up
    the box that the median line is drawn.}
  \item{inches}{If \code{inches} is \code{FALSE}, the units are taken
    to be those of the x axis.  If \code{inches} is \code{TRUE},
    the symbols are scaled so that the largest symbol is one
    inch in height.  If a number is given the symbols are scaled to
    make largest symbol this height in inches.}
  \item{add}{if \code{add} is \code{TRUE}, the symbols are added to
    an existing plot, otherwise a new plot is created.}
  \item{fg}{colors the symbols are to be drawn in (the default is
    the value of the \code{col} graphics parameter).}
  \item{bg}{if specified, the symbols are filled with this color.
    The default is to leave the symbols unfilled. }
  \item{xlab}{the x label of the plot if \code{add} is not true; this
    applies to the following arguments as well.  Defaults to the
    \code{\link{deparse}}d expression used for \code{x}.}
  \item{ylab}{the y label of the plot.}
  \item{main}{a main title for the plot.}
  \item{xlim}{numeric of length 2 giving the x limits for the plot.}
  \item{ylim}{numeric of length 2 giving the y limits for the plot.}
  \item{\dots}{graphics parameters can also be passed to this function,
    as can the plot aspect ratio \code{asp} (see \code{\link{plot.window}}).}
}
\details{
  Observations which have missing coordinates or missing size
  parameters are not plotted.  The exception to this is \emph{stars}.
  In that case, the length of any rays which are \code{NA} is reset
  to zero.

  Circles of radius zero are plotted at radius one pixel (which is
  device-dependent).
#ifdef windows
  On \code{\link{windows}} devices circles are plotted
  at radius at least one pixel as some Windows versions omit smaller
  circles.
#endif
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.

  W. S. Cleveland (1985)
  \emph{The Elements of Graphing Data.}
  Monterey, California: Wadsworth.
}
\seealso{\code{\link{stars}} for drawing \emph{stars} with a bit more
  flexibility; \code{\link{sunflowerplot}}.
}
\examples{
x <- 1:10
y <- sort(10*runif(10))
z <- runif(10)
z3 <- cbind(z, 2*runif(10), runif(10))
symbols(x, y, thermometers=cbind(.5, 1, z), inches=.5, fg = 1:10)
symbols(x, y, thermometers = z3, inches=FALSE)
text(x,y, apply(format(round(z3, dig=2)), 1, paste, collapse = ","),
     adj = c(-.2,0), cex = .75, col = "purple", xpd=NA)

data(trees)
## Note that  example(trees)  shows more sensible plots!
N <- nrow(trees)
attach(trees)
## Girth is diameter in inches
symbols(Height, Volume, circles=Girth/24, inches=FALSE,
        main="Trees' Girth")# xlab and ylab automatically
## Colors too:
palette(rainbow(N, end = 0.9))
symbols(Height, Volume, circles=Girth/16, inches=FALSE, bg = 1:N,
        fg="gray30", main="symbols(*, circles=Girth/16, bg = 1:N)")
palette("default"); detach()
}
\keyword{aplot}
\keyword{hplot}
\keyword{multivariate}
\eof
\name{text}
\title{Add Text to a Plot}
\usage{
text(x, \dots)

\method{text}{default} (x, y = NULL, labels = seq(along = x), adj = NULL,
     pos = NULL, offset = 0.5, vfont = NULL,
     cex = 1, col = NULL, font = NULL, xpd = NULL, \dots)
}
\alias{text}
\alias{text.default}
\arguments{
  \item{x, y}{numeric vectors of coordinates where the text
    \code{labels} should be written.  If the length of \code{x} and
    \code{y} differs, the shorter one is recycled.}
  \item{labels}{one or more character strings or expressions specifying
    the \emph{text} to be written.  An attempt is made
    to coerce other vectors to character, and other language objects
    to expressions.}
  \item{adj}{one or two values in \eqn{[0,1]} which specify the x
    (and optionally y) adjustment of the labels.  On most devices values
    outside that interval will also work.}
  \item{pos}{a position specifier for the text.  If specified this
    overrides any \code{adj} value given.  Values of \code{1},
    \code{2}, \code{3} and \code{4}, respectively indicate
    positions below, to the left of, above and to the right of
    the specified coordinates.}
  \item{offset}{when \code{pos} is specified, this value gives the
    offset of the label from the specified coordinate in fractions
    of a character width.}
  \item{vfont}{if a character vector of length 2 is specified, then Hershey
    vector fonts are used.  The first element of the vector
    selects a typeface and the second element selects a style.}
  \item{cex}{numeric \bold{c}haracter \bold{ex}pansion factor; multiplied
    by \code{\link{par}("cex")} yields the final character size.}
  \item{col, font}{the color and font to be used; these default to the
    values of the global graphical parameters in \code{\link{par}()}.}
  \item{xpd}{(where) should clipping take place?  Defaults to
    \code{\link{par}("xpd")}.}
  \item{\dots}{further graphical parameters (from \code{\link{par}}).}
%% such as ???, etc.
}
\description{
  \code{text} draws the strings given in the vector \code{labels} at the
  coordinates given by \code{x} and \code{y}.
  \code{y} may be missing since \code{\link{xy.coords}(x,y)} is used for
  construction of the coordinates.
}
\details{
  \code{labels} must be of type \code{\link{character}} or
  \code{\link{expression}} (or be coercible to such a type).
  In the latter case, quite a bit of
  mathematical notation is available such as sub- and superscripts,
  greek letters, fractions, etc.

  \code{adj} allows \emph{adj}ustment of the text with respect to \code{(x,y)}.
  Values of 0, 0.5, and 1 specify left/bottom, middle and
  right/top, respectively.  The default is for centered text, i.e.,
  \code{adj = c(0.5, 0.5)}. Accurate vertical centering needs
  character metric information on individual characters, which is
  only available on some devices.

  The \code{pos} and \code{offset} arguments can be used in conjunction
  with values returned by \code{identify} to recreate an interactively
  labelled plot.

  Text can be rotated by using graphical parameters \code{srt} (see
  \code{\link{par}}); this rotates about the centre set by \code{adj}.

  Graphical parameters \code{col}, \code{cex} and \code{font} can be
  vectors and will then be applied cyclically to the \code{labels} (and
  extra values will be ignored).

  Labels whose \code{x}, \code{y}, \code{labels}, \code{cex} or \code{col}
  value is \code{NA} are omitted from the plot.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{mtext}}, \code{\link{title}},
  \code{\link{Hershey}} for details on Hershey vector fonts,
  \code{\link{plotmath}} for details and more examples on
  mathematical annotation.
}
\examples{
plot(-1:1,-1:1, type = "n", xlab = "Re", ylab = "Im")
K <- 16; text(exp(1i * 2 * pi * (1:K) / K), col = 2)

## The following two examples use latin1 characters: these may not
## appear correctly (or be omitted entirely).
plot(1:10, 1:10, main = "text(...) examples\n~~~~~~~~~~~~~~",
     sub = "R is GNU ©, but not ® ...")
mtext("«ISO-accents»: ± éè øØ å<Å æ<Æ", side=3)
points(c(6,2), c(2,1), pch = 3, cex = 4, col = "red")
text(6, 2, "the text is CENTERED around (x,y) = (6,2) by default",
     cex = .8)
text(2, 1, "or Left/Bottom - JUSTIFIED at (2,1) by 'adj = c(0,0)'",
     adj = c(0,0))
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)", cex = .75)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))

## Two more latin1 examples
text(5,10.2,
     "Le français, c'est façile: Règles, Liberté, Egalité, Fraternité...")
text(5,9.8, "Jetz no chli züritüütsch: (noch ein bißchen Zürcher deutsch)")
}
\keyword{aplot}
\eof
\name{title}
\title{Plot Annotation}
\usage{
title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
      line = NA, outer = FALSE, \dots)
}
\alias{title}
\arguments{
  \item{main}{The main title (on top) using font and size (character
    expansion) \code{par("font.main")} and color
    \code{par("col.main")}.}
  \item{sub}{Sub-title (at bottom) using font and size
    \code{par("font.sub")} and color \code{par("col.sub")}.}
  \item{xlab}{X axis label using font and character expansion
    \code{par("font.axis")} and color \code{par("col.axis")}.}
  \item{ylab}{Y axis label, same font attributes as \code{xlab}.}
  \item{line}{specifying a value for \code{line} overrides the
    default placement of labels, and places them this many lines
    from the plot.}
  \item{outer}{a logical value.  If \code{TRUE}, the titles are
    placed in the outer margins of the plot.}
  \item{\dots}{further graphical parameters from
    \code{\link{par}}.  Use e.g., \code{col.main} or \code{cex.sub}
    instead of just \code{col} or \code{cex}.}
}
\description{
  This function can be used to add labels to a plot.  Its first four
  principal arguments can also be used as arguments in most high-level
  plotting functions.  They must be of type \code{\link{character}} or
  \code{\link{expression}}. In the latter case, quite a bit of
  mathematical notation is available such as sub- and superscripts,
  greek letters, fractions, etc.
}
\details{
  The labels passed to title can be simple strings or expressions,
  or they can be a list containing the string to be plotted, and
  a selection of the optional modifying graphical parameters
  \code{cex=}, \code{col=}, \code{font=}.
}
\references{
  Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
  \emph{The New S Language}.
  Wadsworth \& Brooks/Cole.
}
\seealso{
  \code{\link{mtext}}, \code{\link{text}};
  \code{\link{plotmath}} for details on mathematical annotation.
}
\examples{
data(cars)
plot(cars, main = "") # here, could use main directly
title(main = "Stopping Distance versus Speed")

plot(cars, main = "")
title(main = list("Stopping Distance versus Speed", cex=1.5,
                  col="red", font=3))

## Specifying "..." :
plot(1, col.axis = "sky blue", col.lab = "thistle")
title("Main Title", sub = "sub title",
      cex.main = 2,   font.main= 4, col.main= "blue",
      cex.sub = 0.75, font.sub = 3, col.sub = "red")


x <- seq(-4, 4, len = 101)
y <- cbind(sin(x), cos(x))
matplot(x, y, type = "l", xaxt = "n",
        main = expression(paste(plain(sin) * phi, "  and  ",
                                plain(cos) * phi)),
        ylab = expression("sin" * phi, "cos" * phi), # only 1st is taken
        xlab = expression(paste("Phase Angle ", phi)),
        col.main = "blue")
axis(1, at = c(-pi, -pi/2, 0, pi/2, pi),
     lab = expression(-pi, -pi/2, 0, pi/2, pi))
abline(h = 0, v = pi/2 * c(-1,1), lty = 2, lwd = .1, col = "gray70")
}
\keyword{aplot}
\eof
\name{xfig}
\alias{xfig}
\title{XFig Graphics Device}
\description{
  \code{xfig} starts the graphics device driver for producing XFig
  (version 3.2) graphics.

  The auxiliary function \code{ps.options} can be used to set and view
  (if called without arguments) default values for the arguments to
  \code{xfig} and \code{postscript}.
}
\usage{
xfig(file = ifelse(onefile, "Rplots.fig", "Rplot\%03d.fig"),
     onefile = FALSE, \dots)
}
\arguments{
  \item{file}{a character string giving the name of the file.  If it is
    \code{""}, the output is piped to the command given by the argument
    \code{command}.  For use with \code{onefile=FALSE} give a
    \code{printf} format such as \code{"Rplot\%d.fig"} (the default in
    that case).}
  \item{onefile}{logical: if true allow multiple figures
    in one file. If false, assume only one page per file and generate a
    file number containing the page number.}
  \item{\dots}{further arguments to \code{\link{ps.options}} accepted by
    \code{xfig()}:
    \describe{
      \item{\code{paper}}{the size of paper in the printer.  The choices
	are \code{"A4"}, \code{"Letter"} and \code{"Legal"} (and these
	can be lowercase).  A further choice is \code{"default"}, which
	is the default.  If this is selected, the papersize is taken
	from the option \code{"papersize"} if that is set and to
	\code{"A4"} if it is unset or empty.}
      \item{\code{horizontal}}{the orientation of the printed image, a
	logical.  Defaults to true, that is landscape orientation.}
      \item{\code{width}, \code{height}}{the width and height of the
	graphics region in inches.  The default is to use the entire
	page less a 0.25 inch border.}
      \item{\code{family}}{the font family to be used.  This must be one
	of \code{"AvantGarde"}, \code{"Bookman"}, \code{"Courier"},
	\code{"Helvetica"}, \code{"Helvetica-Narrow"},
	\code{"NewCenturySchoolbook"}, \code{"Palatino"} or
	\code{"Times"}.}
      \item{\code{pointsize}}{the default point size to be used.}
      \item{\code{bg}}{the default background color to be used.}
      \item{\code{fg}}{the default foreground color to be used.}
      \item{\code{pagecentre}}{logical: should the device region be
	centred on the page: defaults to \code{TRUE}.}
    }
  }
}
%%>>> REAL DOC in SOURCE:    ../../../main/devices.c  &   ../../../unix/devPS.c
\details{
  Although \code{xfig} can produce multiple plots in one file, the XFig
  format does not say how to separate or view them.  So
  \code{onefile=FALSE} is the default.
}
\note{
  On some line textures (\code{0 <= lty > 4}) are used.  Eventually this
  will be partially remedied, but the XFig file format does not allow as
  general line textures as the \R model.  Unimplemented line textures
  are displayed as \emph{dash-double-dotted}.

  There is a limit of 512 colours (plus white and black) per file.
}
\seealso{
  \code{\link{Devices}},
  \code{postscript},
  \code{\link{ps.options}}.
}
\keyword{device}
\eof
\name{xy.coords}
\title{Extracting Plotting Structures}
\description{
  \code{xy.coords} is used by many functions to obtain
  x and y coordinates for plotting.
  The use of this common mechanism across all \R functions
  produces a measure of consistency.
}
\usage{
xy.coords(x, y, xlab = NULL, ylab = NULL, log = NULL, recycle = FALSE)
}
\alias{xy.coords}
\arguments{
  \item{x, y}{the x and y coordinates of a set of points.
    Alternatively, a single argument \code{x} can be provided.}
  \item{xlab,ylab}{names for the x and y variables to be extracted.}
  \item{log}{character, \code{"x"}, \code{"y"} or both, as for
    \code{\link{plot}}.  Sets negative values to \code{\link{NA}} and
    gives a warning.}
\item{recycle}{logical; if \code{TRUE}, recycle (\code{\link{rep}}) the shorter
    of \code{x} or \code{y} if their lengths differ.}
}
\details{
  An attempt is made to interpret the arguments \code{x} and \code{y} in
  a way suitable for plotting.

  If \code{y} is missing and \code{x} is a
  \describe{
    \item{formula:}{of the form \code{yvar ~ xvar}. \code{xvar} and
      \code{yvar} are used as x and y variables.}

    \item{list:}{containing components \code{x} and \code{y}, these are
      used to define plotting coordinates.}

    \item{time series:}{the x values are taken to be
      \code{\link[stats]{time}(x)} and the y values to be the time series.}

    \item{matrix with two columns:}{the first is assumed to contain the
      x values and the second the y values.}
  }
  In any other case, the \code{x} argument is coerced to a vector and
  returned as \bold{y} component where the resulting \code{x} is just
  the index vector \code{1:n}.  In this case, the resulting \code{xlab}
  component is set to \code{"Index"}.

  If \code{x} (after transformation as above) inherits from class
  \code{"POSIXt"} it is coerced to class \code{"POSIXct"}.
}
\value{
  A list with the components
  \item{x}{numeric (i.e., \code{"double"}) vector of abscissa values.}
  \item{y}{numeric vector of the same length as \code{x}.}
  \item{xlab}{\code{character(1)} or \code{NULL}, the \sQuote{label} of
    \code{x}.}
  \item{ylab}{\code{character(1)} or \code{NULL}, the \sQuote{label} of
    \code{y}.}
}
\seealso{
  \code{\link{plot.default}}, \code{\link{lines}}, \code{\link{points}}
  and \code{\link[stats]{lowess}} are examples of functions which use this mechanism.
}
\examples{
xy.coords(fft(c(1:10)), NULL)
data(cars)
with(cars, xy.coords(dist ~ speed, NULL)$xlab ) # = "speed"

xy.coords(1:3, 1:2, recycle=TRUE)
xy.coords(-2:10,NULL, log="y")
##> warning: 3 y values <=0 omitted ..
}
\keyword{dplot}
\eof
\name{xyz.coords}
\alias{xyz.coords}
\title{Extracting Plotting Structures}
\description{
  Utility for obtaining consistent x, y and z coordinates and labels
  for three dimensional (3D) plots.
}
\usage{
xyz.coords(x, y, z, xlab=NULL, ylab=NULL, zlab=NULL, log=NULL,
    recycle=FALSE)
}
\arguments{
  \item{x, y, z}{the x, y and z coordinates of a set of points.
    Alternatively, a single argument \code{x} can be provided.
    In this case, an attempt is made to interpret the
    argument in a way suitable for plotting.

    If the argument is a formula \code{zvar ~ xvar + yvar},
    \code{xvar}, \code{yvar} and \code{zvar} are used as x, y and z
    variables;
    if the argument is a list containing components \code{x},
    \code{y} and \code{z}, these are assumed to define plotting coordinates;
    if the argument is a matrix with three columns, the first is
    assumed to contain the x values, etc.

    Alternatively, two arguments \code{x} and \code{y} can be provided.
    One may be real, the other complex;
    in any other case, the arguments are coerced to vectors
    and the values plotted against their indices.
  }
  \item{xlab, ylab, zlab}{names for the x, y and z variables to be extracted.}
  \item{log}{character, \code{"x"}, \code{"y"}, \code{"z"} or combinations.
    Sets negative values to \code{\link{NA}} and gives a warning.}
  \item{recycle}{logical; if \code{TRUE}, recycle (\code{\link{rep}}) the
    shorter ones of \code{x}, \code{y} or \code{z} if their lengths differ.}
}
\value{
  A list with the components
  \item{x}{numeric (i.e., \code{\link{double}}) vector of abscissa values.}
  \item{y}{numeric vector of the same length as \code{x}.}
  \item{z}{numeric vector of the same length as \code{x}.}
  \item{xlab}{\code{character(1)} or \code{NULL}, the axis label of \code{x}.}
  \item{ylab}{\code{character(1)} or \code{NULL}, the axis label of \code{y}.}
  \item{zlab}{\code{character(1)} or \code{NULL}, the axis label of \code{z}.}
}
\author{Uwe Ligges and Martin Maechler}
\seealso{\code{\link{xy.coords}} for 2D.}
\examples{
xyz.coords(data.frame(10*1:9, -4), y = NULL, z = NULL)

xyz.coords(1:6, fft(1:6), z = NULL, xlab="X", ylab="Y")

y <- 2 * (x2 <- 10 + (x1 <- 1:10))
xyz.coords(y ~ x1 + x2, y = NULL, z = NULL)

xyz.coords(data.frame(x=-1:9, y=2:12, z=3:13), y = NULL, z = NULL, log="xy")
##> Warning message: 2 x values <= 0 omitted ...
}
\keyword{dplot}
\eof
\name{Gnome}
\alias{GNOME}
\alias{gnome}
\title{GNOME Desktop Graphics Device}
\description{
  \code{gnome} starts a \acronym{GNOME} compatible device driver.
  \acronym{GNOME} is an acronym for \bold{G}NU \bold{N}etwork
  \bold{O}bject \bold{M}odel \bold{E}nvironment.
}
\usage{
gnome(display="", width=7, height=7, pointsize=12)
GNOME(display="", width=7, height=7, pointsize=12)
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
}
\references{\url{http://www.gnome.org} and \url{http://www.gtk.org} for
  the \code{GTK+} (GIMP Tool Kit) libraries.
}
\author{Lyndon Drake \email{lyndon@stat.auckland.ac.nz}}
\note{
  This device was never completed, and will be removed in R 2.0.0.

  The GNOME device is only available when explicitly desired at
  configure/compile time, see the toplevel \file{INSTALL} file.
}
\seealso{\code{\link{x11}}, \code{\link{Devices}}.}
\examples{
\dontrun{
gnome(width=9)
}
}
\keyword{device}
\eof
\name{png}
\alias{png}
\alias{jpeg}
\title{JPEG and PNG graphics devices}
\description{
  A graphics device for JPEG or PNG format bitmap files.
}
\usage{
jpeg(filename = "Rplot\%03d.jpeg", width = 480, height = 480,
     pointsize = 12, quality = 75, bg = "white", \dots)
png(filename ="Rplot\%03d.png", width = 480, height = 480,
    pointsize = 12, bg = "white", \dots)
}
\synopsis{
jpeg(filename = "Rplot\%03d.jpeg", width = 480, height = 480, pointsize = 12,
     quality = 75, gamma = 1,
     colortype = getOption("X11colortype"), maxcubesize = 256, bg = "white",
    fonts = getOption("X11fonts"))
png(filename ="Rplot\%03d.png", width = 480, height = 480, pointsize = 12,
    gamma = 1, colortype = getOption("X11colortype"), maxcubesize = 256,
    bg = "white", fonts = getOption("X11fonts"))
}
\arguments{
  \item{filename}{the name of the output file.
    The page number is substituted if an integer format is included
    in the character string. (The result must be less than \code{PATH_MAX}
    characters long, and may be truncated if not.)
    Tilde expansion is performed where supported by the platform.}
  \item{width}{the width of the device in pixels.}
  \item{height}{the height of the device in pixels.}
  \item{pointsize}{the default pointsize of plotted text.}
  \item{quality}{the \sQuote{quality} of the JPEG image, as a
    percentage.  Smaller values will give more compression but also more
    degradation of the image.}
  \item{bg}{default background colour.}
  \item{\dots}{additional arguments to the \code{\link{X11}} device.}
}
\details{
  Plots in PNG and JPEG format can easily be converted to many other
  bitmap formats, and both can be displayed in most modern web
  browsers. The PNG format is lossless and is best for line
  diagrams and blocks of solid colour. The JPEG format is lossy,
  but may be useful for image plots, for example.

  \code{png} supports transparent backgrounds: use \code{bg = "transparent"}.
  Not all PNG viewers render files with transparency correctly.
  When transparency is in use a very light grey is used as the
  background and so will appear as transparent if used in the plot.
  This allows opaque white to be used, as on the example.

  \R can be compiled without support for either or both of these
  devices: this will be reported if you attempt to use them on a system
  where they are not supported.  They will not be available if \R has
  been started with \samp{--gui=none} (and will give a different error
  message), and they may not be usable unless the X11 display is
  available to the owner of the \R process.
}
\value{
  A plot device is opened: nothing is returned to the \R interpreter.
}
\section{Warning}{
  If you plot more than one page on one of these devices and do not
  include something like \code{\%d} for the sequence number in
  \code{file}, the file will contain the last page plotted.
}
\note{
  These are based on the \code{\link{X11}} device, so the additional
  arguments to that device work, but are rarely appropriate.  The
  colour handling will be that of the \code{X11} device in use.
}
\author{Guido Masarotto and Brian Ripley}

\seealso{
  \code{\link{Devices}}, \code{\link{dev.print}}

  \code{\link{capabilities}} to see if these devices are
  supported by this build of \R.

  \code{\link{bitmap}} provides an alternative way to generate PNG and
  JPEG plots that does not depend on accessing the X11 display but does
  depend on having GhostScript installed.
}
\examples{
## these examples will work only if the devices are available
## and the X11 display is available.

## copy current plot to a PNG file
\dontrun{dev.print(png, file="myplot.png", width=480, height=480)

png(file="myplot.png", bg="transparent")
plot(1:10)
rect(1, 5, 3, 7, col="white")
dev.off()

jpeg(file="myplot.jpeg")
example(rect)
dev.off()
}}
\keyword{device}
\eof
\name{quartz}
\alias{quartz}
\title{MacOS X Quartz device}
\description{
  \code{quartz} starts a graphics device driver for the MacOS X System.
  This can only be done on machines that run MacOS X.
}
\usage{
quartz(display = "", width = 5, height = 5, pointsize = 12,
       family = "Helvetica", antialias = TRUE, autorefresh = TRUE)
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
  \item{family}{this is the family name of the Postscript font
    that will be used by the device.}
  \item{antialias}{whether to use antialiasing. It is never the case to set
     it \code{FALSE}}
  \item{autorefresh}{logical specifying if realtime refreshing should be
    done.  If \code{FALSE}, the system is charged to refresh the context
      of the device window.}
 }
\details{
  Quartz is the graphic engine based on the PDF format.  It is used
  by the graphic interface of MacOS X to render high quality graphics.
  As PDF it is device independent and can be rescaled without loss of
  definition.

  Calling \code{quartz()} sets \code{\link{.Device}} to \code{"quartz"}.
}
\seealso{
  \code{\link{Devices}}.
}
\keyword{device}
\eof
\name{x11}
\alias{x11}
\alias{X11}
\title{X Window System Graphics}
\description{
  \code{X11} starts a graphics device driver for the X Window System
  (version 11).  This can only be done on machines that run X.
  \code{x11} is recognized as a synonym for \code{X11}.
}
\usage{
X11(display = "", width = 7, height = 7, pointsize = 12,
    gamma = 1, colortype = getOption("X11colortype"),
    maxcubesize = 256, canvas = "white",
    fonts = getOption("X11fonts"))
}
\arguments{
  \item{display}{the display on which the graphics window will appear.
    The default is to use the value in the user's environment variable
    \env{DISPLAY}.}
  \item{width}{the width of the plotting window in inches.}
  \item{height}{the height of the plotting window in inches.}
  \item{pointsize}{the default pointsize to be used.}
  \item{gamma}{the gamma correction factor.  This value is used
    to ensure that the colors displayed are linearly related to
    RGB values.  A value of around 0.5 is appropriate for many PC
    displays.  A value of 1.0 (no correction) is usually appropriate
    for high-end displays or Macintoshs.}
  \item{colortype}{the kind of color model to be used.  The
    possibilities are \code{"mono"}, \code{"gray"}, \code{"pseudo"},
    \code{"pseudo.cube"} and \code{"true"}. Ignored if an \code{X11} is
    already open.}
  \item{maxcubesize}{can be used to limit the size of color
    cube allocated for pseudocolor devices.}
  \item{canvas}{color.  The color of the canvas, which is visible only
    when the background color is transparent.}
  \item{fonts}{X11 font description strings into which weight, slant and
    size will be substituted.  There are two, the first for fonts 1 to 4
    and the second for font 5, the symbol font.}
}
\details{
  By default, an X11 device will use the best color rendering
  strategy that it can.  The choice can be overriden with the
  \code{colortype} parameter.  A value of \code{"mono"} results in
  black and white graphics, \code{"gray"} in grayscale and
  \code{"true"} in truecolor graphics (if this is possible).  The
  values \code{"pseudo"} and \code{"pseudo.cube"} provide color
  strategies for pseudocolor displays.  The first strategy provides
  on-demand color allocation which produces exact colors until
  the color resources of the display are exhausted.  The second
  causes a standard color cube to be set up, and requested colors
  are approximated by the closest value in the cube.  The default
  strategy for pseudocolor displays is \code{"pseudo"}.

  \bold{Note:} All \code{X11} devices share a \code{colortype} which is
  set by the first device to be opened.  To change the \code{colortype}
  you need to close \emph{all} open \code{X11} devices then open one
  with the desired \code{colortype}.

  With \code{colortype} equal to \code{"pseudo.cube"} or \code{"gray"}
  successively smaller palettes are tried until one is completely
  allocated. If allocation of the smallest attempt fails the device will
  revert to \code{"mono"}.
}
\seealso{
  \code{\link{Devices}}.
}
\keyword{device}
\eof
