[R] Legend in the Margins of a plot

Jim Lemon bitwrit at ozemail.com.au
Thu May 13 14:56:46 CEST 1999


Partha,

If you mean the style of legend below or above the plot as often seen in
charting programs, this might be what you need.  You may have to set the
margins to get this to work - e.g.

>par(mar=c(7,4,4,2))

> plot(1:10,xlab="")
> legend.mar(legend=c("First","Second","Third"),lty=1:3,pch=1:3,col=1:3)

The function is as follows:

> legend.mar
function (side = 1, xpos, ypos, legend, lty, pch, col)
{
    if (!missing(legend)) {
        oldpar <- par("adj","xpd)
        par(adj = 0, xpd = T)
        legendwidth <- strwidth(legend)
        markwidth <- strwidth("MM")
        totalwidth <- sum(legendwidth) + 3 * markwidth * length(legend)
        if (missing(xpos)) {
            xlim <- par("usr")[1:2]
            xcenter <- (xlim[1] + xlim[2])/2
            xpos <- xcenter - totalwidth/2
        }
        if (missing(ypos)) {
            ylim <- par("usr")[3:4]
            yoffset <- (ylim[2] - ylim[1])/6
            if (side != 1)
                ypos <- ylim[2] + yoffset
            else ypos <- ylim[1] - yoffset
        }
        if (missing(col))
            col <- rep(1, length(legend))
        for (i in 1:length(legend)) {
            if (!missing(pch))
                points(xpos, ypos, type = "p", pch = pch[i],
                  col = col[i])
            if (!missing(lty))
                lines(c(xpos - markwidth, xpos), c(ypos, ypos),
                  type = "l", lty = lty[i], col = col[i])
            xpos <- xpos + markwidth
            text(xpos, ypos, legend[i])
            xpos <- xpos + legendwidth[i] + 2 * markwidth
        }
        par(oldpar)
    }
    else cat("Usage: legend.mar([side=1] [, xpos] [, ypos], legend [,
lty] [, pch] [, col=1])\n")
}


Bit rough, but I hope it helps.

Jim


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list