Mark Heckmann
Mark Heckmann

Reputation: 11441

How to get the width and height of a character in usr coordinates

How can I get the width and height of a character in usr coordinates? I found something on R-help, but that appears not to make it completely clear. I assumed that

plot(NULL, xlim=c(-1,1), ylim=c(-1,1))
h <- par()$cxy
rect(-h[1]/2, -h[2]/2, h[1]/2, h[2]/2)
text(0,0,"M")

enter image description here

would be the answer but the rectangle is slightly too big. Additionally I want the size also to respect different cex values. Thanks for your time!

Upvotes: 3

Views: 659

Answers (1)

Mark Heckmann
Mark Heckmann

Reputation: 11441

I finally discovered an answer in the par docu:

cxy

R.O.; size of default character (width, height) in user coordinate units. par("cxy") is par("cin")/par("pin") scaled to user coordinates. Note that c(strwidth(ch), strheight(ch)) for a given string ch is usually much more precise.

Using strwidth and strheight instead of par()$cxy gives much better results.

plot(NULL, xlim=c(-1,1), ylim=c(-1,1))
h <- c(strwidth("M"), strheight("M"))
rect(-h[1]/2, -h[2]/2, h[1]/2, h[2]/2)
text(0,0,"M")

enter image description here

Upvotes: 1

Related Questions