[R] How do I exactly align the right hand side of "mtext" relative to a plot device? Beyond "adj".

Marc Schwartz marc_schwartz at me.com
Wed Jan 18 21:58:25 CET 2012


On Jan 18, 2012, at 1:14 PM, George Shirreff wrote:

> Hi,
> 
> I have a problem with aligning text which I'm adding to a plot using
> "mtext". I would like to specify the position of the right hand end of the
> text string, relative to the device (in the left-right direction).
> 
> I've been looking at the use of the argument "adj". But this can't be used
> to specify the rightmost point of the text. Neither does it specify exactly
> the centre of the text, so I'm not sure exactly how it works.
> 
> I could hack it and change "adj" accordingly but this is part of a function
> which I need to generalise. So it needs to be the same regardless of the
> length of the added text, or the values on the x-axis.
> 
> Here's a simple example with two versions (the first three lines of each
> version are identical). I would like the right end of the added text to be
> the same distance from the legend in both versions.
> 
> ### v1
> dev.new()
> plot(c(0,1),c(0,1),ylim=c(0,2))
> legend("topright",c("data1","data2"),col=c(1,2),lty=1,bty="n")
> mtext("text",side=3,line=-2,adj=0.8)
> 
> ### v2
> dev.new()
> plot(c(0,1),c(0,1),ylim=c(0,2))
> legend("topright",c("data1","data2"),col=c(1,2),lty=1,bty="n")
> mtext("really long text",side=3,line=-2,adj=0.8)
> 
> 
> Thank you for your help,
> George


It's not clear to me why you are using mtext() rather than text(). The former is typically used for placing text in the margins of a plot, hence the 'm' prefix. Also, text() has a 'pos' argument which allows you to align text.

Further, legend() returns a list which provides information on the position of the legend drawn and the text inside of it. See the Value section of ?legend.

So, something like the following might work for you:

plot(c(0,1),c(0,1),ylim=c(0,2))

POS <- legend("topright",c("data1","data2"),col=c(1,2),lty=1,bty="n")

# See the content of 'POS' from legend():
> POS
$rect
$rect$w
[1] 0.2047638

$rect$h
[1] 0.2511628

$rect$left
[1] 0.8352362

$rect$top
[1] 2.08


$text
$text$x
[1] 0.9477362 0.9477362

$text$y
[1] 1.996279 1.912558


# Now use text(), right aligning the two lines of text so that 
# they are 0.1 to the left of the edge of the legend box.
text(POS$rect$left - 0.1, 1.9, "text", pos = 2)

text(POS$rect$left - 0.1, 2, "really long text", pos = 2)


See ?text.

HTH,

Marc Schwartz



More information about the R-help mailing list