4

I would like to graphically measure the width of a string. (see examples in the attached image. I have used Times New Roman with point size 11 and size 16)

Each character will have different width e.g. "a" vs "A" for the same font & font size. I am trying to look for solution to graphically plot text and programmatically measure the graphical length (in terms of "mm" or "inch") I tried strwidth() function but it is not working correctly. e.g. gives me same value for "a" vs "A"

R - Measure width of string using strwidth()

enter image description here

Community
  • 1
  • 1
R007
  • 101
  • 1
  • 13
  • What code and what OS are you using, and what result do you get? I get different widths when I run (on OSX) `strwidth("a", units = "inches", family = "Times New Roman")` [0.07397461] and when I run `strwidth("A", units = "inches", family = "Times New Roman")` [0.1203613] so I can't reproduce your issue. – Jon Spring Jan 04 '20 at 02:34
  • Sorry I was trying strwidth("a", units = "inches", family = "Times New Roman", font=11). that font=11 is causing some issue. How can I specify font size ? – R007 Jan 04 '20 at 02:42

1 Answers1

3

It looks like you'll need to use par() with the ps argument.

 strwidth("This is a test.", units = "inches", family = "Arial", ps = par(ps = 11))
[1] 0.875

> strwidth("This is a test.", units = "inches", family = "Arial", ps = par(ps = 16))
[1] 1.333333

> strwidth("This is a test.", units = "inches", family = "Times New Roman", ps = par(ps = 16))
[1] 1.145833

> strwidth("This is a test.", units = "inches", family = "Times New Roman", ps = par(ps = 11))
[1] 0.8333333

> strwidth("This is a test.", units = "inches", family = "Times New Roman", ps = par(ps = 24))
[1] 1.75

A quick measure in a google doc, and it looks about right.

mrhellmann
  • 5,069
  • 11
  • 38