[R] strwidth and strheight for rotated text

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 7 12:16:08 CET 2007

```See ?par, 'cxy' for how to go from width/heights in inches to user
coordinates and vice versa.  You appear to have overlooked 'pin'.

On Wed, 7 Nov 2007, Stéphane Dray wrote:

> Dear All,
> I would like to plot text with a box around it. I used strwidth and
> strheight to compute the size of the box which is plotted with rect:
>
> z <- rnorm(10)
>
> # horizontal text works
> plot(rnorm(10))
> x1 <- 5
> y1 <- 0
> label <- "Label"
> cha <- paste(" ", label, " ", sep = "")
> xh <- strwidth(cha, cex = par("cex"))
> yh <- strheight(cha, cex = par("cex")) * 5/3
> rect(x1 - xh/2, y1 - yh/2, x1 + xh/2, y1 + yh/2, col = "white")
> text(x1, y1, cha, cex = par("cex"))
>
> Now I would like to do the same with rotated text. I found two solutions:
> -  modify the par("usr")
> -  compute ratio to transform width and height computed on the unrotated
> text.
>
> These two solutions work for square graphic window (e.g. X11(),
> X11(width=3, height=3)..)
>
> But the two solutions does not work for rectangular windows:
>
> # does not works for rotated text using modif of par("usr")
> X11(height=4)
> plot(z)
> x1 <- 5
> y1 <- 0
> xusr <- par("usr")
> par("usr"=xusr[c(3,4,1,2)])
> yh <- strwidth(cha, cex = par("cex"))
> xh <- strheight(cha, cex = par("cex")) * 5/3
> par("usr"=xusr)
> rect(x1 - xh/2, y1 - yh/2, x1 + xh/2, y1 + yh/2, col = "white")
> text(x1, y1, cha, cex = par("cex"), srt = 90)
>
> # does not works for rotated text using manual modification of xh and yh
> X11(height=4)
> plot(z)
> x1 <- 5
> y1 <- 0
> xusr <- par("usr")
> xh <- strwidth(cha, cex = par("cex"))
> yh <- strheight(cha, cex = par("cex")) * 5/3
> tmp <- yh
> yh <- xh/(xusr[2]-xusr[1])*(xusr[4]-xusr[3])
> xh <- tmp/(xusr[4]-xusr[3])*(xusr[2]-xusr[1])
> rect(x1 - xh/2, y1 - yh/2, x1 + xh/2, y1 + yh/2, col = "white")
> text(x1, y1, cha, cex = par("cex"), srt = 90)
>
>
>
> I can not understand why it does not work. Any help would be very
> appreciated.
>
> > sessionInfo()
> R version 2.6.0 (2007-10-03)
> i686-pc-linux-gnu
>
> locale:
>
>
>
> Cheers.
>
>
>

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595
```