[R] Legends and Fonts

Jim Lemon bitwrit at ozemail.com.au
Fri Aug 23 16:07:11 CEST 2002


Ronnen Levinson wrote:
> Hello.
>
> Is it possible to set specify the font used by legend()? I would like to
> specify a fixed-width font so that I can line up parts of vertically
> stacked curve labels. For example, it would be nice if I could align the
> names, ages, and weights in the following three curve labels:
>
>     Bob age=7 weight=100
>     Alexander age=13 weight=150
>     Susan age=20 weight=130
>
> Is there perhaps a clever solution involving expression()?
>
Don't know how clever it is, but this might do the job:

> tl<-matrix(c("Bob","Alexander","Susan","Age=7","Age=13","Age=20",
+ "Weight=100","Weight=150","Weight=130"),ncol=3)
> tl
     [,1]        [,2]     [,3]
[1,] "Bob"       "Age=7"  "Weight=100"
[2,] "Alexander" "Age=13" "Weight=150"
[3,] "Susan"     "Age=20" "Weight=130"

longest.string<-function(stringvec) {
 longest<-0
 for(i in 1:length(stringvec))
  if(strwidth(stringvec[i]) > longest) longest<-strwidth(stringvec[i])
 return(longest)
}

tab.list<-function(x,y,tl,margin=0.1) {
 dtl<-dim(tl)
 par(adj=0)
 height<-strheight("M")*1.5
 if(length(dtl) > 1) {
  widths<-vector("numeric",0)
  for(i in 1:dtl[2]) widths[i]<-longest.string(tl[,i])
  xpos<-x
  for(i in 1:dtl[2]) {
   for(j in 1:dtl[1]) {
    ypos<-y-(j-1)*height
    text(xpos,ypos,tl[j,i])
   }
   xpos<-xpos + widths[i] * 1.1
  }
 }
 else {
  width<-longest.string(tl)
  for(j in length(tl)) {
   ypos<-y+(i-1)*height
   text(xpos,ypos,tl[j,i])
  }
 }
 rect(x-margin*(xpos-x),
      ypos - (height + margin*(y-ypos)),
      xpos+margin*(xpos-x),
      y + (height + margin*(y-ypos)))
}

plot(...)
tab.list(x,y,tl)

where x and y are the top left corner of the _text_, and there will be a 
bit of margin left around the text within the box.

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