\Header{legend}{Add Legends to Plots}
\keyword{aplot}{legend}
\begin{Description}\relax
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.
\end{Description}
\begin{Usage}
\begin{verbatim}
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)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{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[\code{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[\code{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[\code{col}] the color of points or lines appearing in the legend.
\item[\code{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[\code{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[\code{angle}] angle of shading lines.
\item[\code{density}] the density of shading lines, if numeric and
positive. If \code{NULL} or negative or \code{NA} color filling
is assumed.
\item[\code{bty}] the type of box to be drawn around the legend.  The allowed
values are \code{"o"} (the default) and \code{"n"}.
\item[\code{bg}] the background color for the legend box.  (Note that this is
only used if \code{bty != "n"}.)
\item[\code{pt.bg}] the background color for the \code{\Link{points}}.
\item[\code{cex}] character expansion factor \bold{relative} to current
\code{par("cex")}.
\item[\code{pt.cex}] expansion factor(s) for the points.
\item[\code{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[\code{yjust}] the same as \code{xjust} for the legend y location.
\item[\code{x.intersp}] character interspacing factor for horizontal (x) spacing.
\item[\code{y.intersp}] the same for vertical (y) line distances.
\item[\code{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[\code{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[\code{text.col}] the color used for the legend text.
\item[\code{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[\code{trace}] logical; if \code{TRUE}, shows how \code{legend} does all
its magical computations.
\item[\code{plot}] logical.  If \code{FALSE}, nothing is plotted but the
sizes are returned.
\item[\code{ncol}] the number of columns in which to set the legend items
(default is 1, a vertical legend).
\item[\code{horiz}] logical; if \code{TRUE}, set the legend horizontally rather than
vertically (specifying \code{horiz} overrides the \code{ncol}
specification).
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
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.
\end{Details}
\begin{Value}
A list with list components
\begin{ldescription}
\item[\code{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[\code{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).
}

\end{ldescription}

returned invisibly.
\end{Value}
\begin{References}\relax
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
\emph{The New S Language}.
Wadsworth \& Brooks/Cole.
\end{References}
\begin{SeeAlso}\relax
\code{\Link{plot}}, \code{\Link{barplot}} which uses \code{legend()}, and
\code{\Link{text}} for more examples of math expressions.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
## 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")
\end{ExampleCode}
\end{Examples}

