[R] Aligning text in the call to the text function

Duncan Murdoch murdoch at stats.uwo.ca
Thu Apr 1 22:15:18 CEST 2010


On 01/04/2010 3:39 PM, Tighiouart, Hocine wrote:
> Hi,
>
> I have text (see below) that is aligned nicely when printed in the
> command window in R but when plotted using text function, it does not
> show alignment unless I use the family="mono" in the call to the text
> function. Is there a way to specify a different font while maintaining
> the alignment?
>
>  Eric & Alan 1667   3   459
>  Alan 2001          45  34
>  John & David 1996  2   5235
>
>   


Plot each of the parts separately, i.e. plot 9 objects, not 3.  You can 
use strwidth() to compute how big each part is and adjust the 
positioning based on that.

You might also be able to do it using paste() and atop() with an 
expression; see ?plotmath.  But I think manual positioning is easiest.  
Here's an example:

leftalign <- function(x, y, m) {
  widths <- strwidth(m)
  dim(widths) <- dim(m)
  widths <- apply(widths, 2, max)
  widths <- widths + strwidth("   ")
  heights <- strheight(m)
  dim(heights) <- dim(m)
  heights <- apply(heights, 1, max)
  heights <- heights*1.5
 
  xoffsets <- c(0, cumsum(widths[-length(widths)]))
  yoffsets <- c(0, -cumsum(heights[-length(heights)]))

  text(x + rep(xoffsets, each=nrow(m)),
       y + rep(yoffsets, ncol(m)), m, adj=c(0,1))

}

plot(1)
leftalign(0.8, 1.2, matrix(c("Eric & Alan 1667", "Alan 2001", "John & 
David 1996", 3,45,2,459,34,5235), ncol=3))

Obviously you could make it a lot more elaborate, with left alignment 
for some columns and right alignment for others, etc.  Probably some 
package has already done this.

Duncan Murdoch



More information about the R-help mailing list