[R] Legend box line thickness

Marc Schwartz MSchwartz at mn.rr.com
Tue Aug 29 03:46:10 CEST 2006


On Mon, 2006-08-28 at 17:55 -0700, Phil Turk wrote:
> I am merely trying to increase the line thickness, or line width, of the box 
> drawn around the legend in a plot I am constructing.  The help page on 
> 'legend' was of no use.  Does anyone have an idea on how to do this?  Please 
> respond to philip.turk at nau.edu.  Thanks!

There are two options.

The easier one is not immediately evident from the help page and
requires reviewing the R code for the legend function, which reveals
that there is an internal function called rect2(), which is built on top
of rect(). It is this function that draws the outer box.

The help page for rect() shows that the line width argument 'lwd' in the
function defaults to par("lwd"). See ?par for more information.

Thus using:

  par(lwd = SomethingGreaterThan1)

before the call to legend will set the box to a wider line thickness.

Be sure to set par(lwd = 1) before any other plot calls to return to the
default setting.



Second, the Value section of ?legend clearly indicates:


Value

A list with list components

rect
a list with components 
w, h
        positive numbers giving
        width and height of the
        legend's box.
left, top
        x and y coordinates of upper
        left corner of the box.
text
a list with components 
x, y
        numeric vectors of length
        length(legend), giving the x
        and y coordinates of the
        legend's text(s).

returned invisibly.



Thus, expanding on the third example in ?legend:

## 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)

# Key call here
temp <- legend("topright", legend = c(" ", " "),
               text.width = strwidth("1,000,000"),
               lty = 1:2, xjust = 1, yjust = 1,
               title = "Line Types")

text(temp$rect$left + temp$rect$w, temp$text$y,
     c("1,000", "1,000,000"), pos=2)


# Now do the legend box using a wide line:
rect(temp$rect$left, temp$rect$top - temp$rect$h, 
     temp$rect$left + temp$rect$w, temp$rect$top + temp$rect$h, lwd = 2)


It would not seem unreasonable to add new arguments to legend(), perhaps
calling them box.lwd and box.lty, which can then be passed to the
rect2() internal function call for the box by modifying the existing
call to:

 rect2(left, top, dx = w, dy = h, col = bg, density = NULL, 
       lwd = box.lwd, lty = box.lty)


HTH,

Marc Schwartz



More information about the R-help mailing list