All posts by BioStatMatt

Descending Text in Righthand Margin of R Graphics à la mtext

There was an R-help thread in January regarding text in the righthand margin of an R graphic, where the text should be rendered in reading order from top to bottom. The base R function mtext is used to plot text in the margin. But, mtext is only able to render text from left to right and bottom to top. The mtext function does not honor the srt plotting parameter, which may be used to rotate text using the text function (see ?par and ?text). Indeed, R Core member Uwe Ligges responded that "You cannot do that with mtext, you rather need a dirty hack with text(), I believe." Below is my dirty hack.

The mtexti function defined below takes arguments that are similar to mtext, with one major exception. Rather than specifying the margin line on which to render the text, the offset (in inches) from the edge of the plotting region is specified instead. Hence, the "i" in mtexti is intended to remind the user of this distinction.

mtexti.R

# text - character, text to be plotted
# side - numeric, 1=bottom 2=left 3=top 4=right
# off  - numeric, offset in inches from the edge of the plotting region
# srt  - string rotation in degrees
# ...  - additional arguments passed to text()
mtexti <- function(text, side, off = 0.25,
                   srt = if(side == 2) 90  else
                         if(side == 4) 270 else 0, ...) {
    # dimensions of plotting region in user units
    usr <- par('usr')
    # dimensions of plotting region in inches
    pin <- par('pin')
    # user units per inch
    upi <- c(usr[2]-usr[1],
             usr[4]-usr[3]) / pin
    # default x and y positions
    xpos <- (usr[1] + usr[2])/2
    ypos <- (usr[3] + usr[4])/2
    if(1 == side)
        ypos <- usr[3] - upi[2] * off
    if(2 == side)
        xpos <- usr[1] - upi[1] * off
    if(3 == side)
        ypos <- usr[4] + upi[2] * off
    if(4 == side)
        xpos <- usr[2] + upi[1] * off
    text(x=xpos, y=ypos, text, xpd=NA, srt=srt, ...)
}

Here is an example:

plot(1, yaxt='n', xaxt='n', xlab='', ylab='', type='n')
mtexti("test", 1)
mtexti("test", 2)
mtexti("test", 3)
mtexti("test", 4)

mtexti-example