# [R] Legends on plots

Thomas Lumley thomas at biostat.washington.edu
Fri Dec 22 18:07:59 CET 2000

```> At 02:49 PM 12/21/00 -0800, Marc Feldesman wrote:
>
>  >the coordinates of the upper left-hand corner.  I prefer the latter
>  >solution, but obviously I have to know that there will be no data points
>  >obscured by this placement.   What is the recommended programming solution
>  >to determine whether enough plot space exists to place the legend in this
>  >location?

There isn't an easy way to do this.  The brute force solution is
straightforward but tedious. You need to write a wrapper for plot that
works out the range of x and y, uses strwidth to work out the amount of
space needed for the legend, and then checks to see if the rectangle of
space it needs contains any points.

It would be easier to add the necessary space rather than working out if
there's enough. The following is general but shows the idea.

The parameter "fudgefactor" depends on the device and text size: its the
number of lines of legend that take up the whole screen.

legend.call is a list of arguments to legend() without the (x,y)

eg
plotwithlegend(x,y,pch=z,legend.call=list(legend=c("one","two"),
pch=1:2,bty="n"))

plotwithlegend<-function(x,y,...,xlim=NULL,ylim=NULL,legend.call=NULL,
fudgefactor=20){
legendlines<-length(legend.call\$legend)
if (is.null(ylim)) ylim<-range(y)
if (is.null(xlim)) xlim<-range(x)
ylim[2]<-ylim[2]+(legendlines+2)*diff(ylim)/(fudgefactor-legendlines)
plot(x,y,...,ylim=ylim)
legend.call\$x<-xlim[1]
legend.call\$y<-ylim[2]
do.call("legend",legend.call)
}

-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```