[R] is it possible to get the coordinate of mtext()?

Jinsong Zhao jszhao at yeah.net
Tue Mar 18 02:00:05 CET 2014


On 2014/3/17 15:32, Jim Lemon wrote:
> On 03/18/2014 09:18 AM, Jinsong Zhao wrote:
>> Hi there,
>>
>> I hope to rotate the Y label of axis(4) with -90 degree. I can typeset
>> the Y label using text() with srt = -90. However, I cannot get the
>> coordinate of the position that mtext() used.
>>
>> In other words, I hope to convert:
>> mtext("Y label", side = 4, at = 0, line = 2)
>> to
>> text(x, 0, "Y label", str = -90)
>>
>> Now, I don't know how to get the x in the above expression. I can give
>> it an arbitrary value. However, I hope it could be more precise.
>>
> Hi Jinsong,
> If you mean the distance from the axis, mtext is placed by a multiple of
> the height of a line of text. Therefore:
>
> strheight("O") * 2
>
> will give you an approximate distance in user units. You can then add
> this to the user coordinate of the right ordinate of the plot:
>
> par("usr")[2]
>
> to get your "x" value. You will probably want to adjust this to get the
> desired visual spacing.
>
> Jim
>

Thank you very much for the hints. It's something complex than that, 
because the strheight("O") is in inch, and that is different with 
par("usr").

The following code may be the exact one I have got.

par(mar=c(4,4,4,4),xpd=NA)
plot(1:10)
axis(4)
mtext("Rain", side = 4, line = 2)
usr <- par("usr")
text((grconvertX(1, "ndc", "user") - usr[2])/2 + usr[2], 
(usr[3]+usr[4])/2, "Rain", srt = 90, adj=c(0.5,1), col = "blue")

As you can see the two "Rain" not overlap very well. The difference may 
be 1 lwd, I don't know. However, I have satisfied with the results very 
well.

Regards,
Jinsong




More information about the R-help mailing list