[R] Adjust cex to fit width

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon May 6 10:02:11 CEST 2013


This does depend on the unstated device.  But on most devices the string 
width is either exactly or approximately proportional to cex.   Some 
devices cannot scale fonts so there is a small set of available sizes: 
in which case you can use uniroot() to find the cex corresponding to the 
closest fit.

Information on which sizes are available is in the device's help page, 
at least for devices provided by the core team.

On 06/05/2013 08:03, Dario Beraldi wrote:
> Hello,
>
> I need to add some text to a plot and I would like this text to be of a
> given width in user coordinates.
>
> I know I can get the width of a string for a given cex using strwidth. But
> how can I do the other way around? How can I get the cex value that will
> make my string of a given width (at least approximately)?
>
> In this example I want my string to have width 50 so the 'target' cex would
> be 1.5, at least on my device:
>
> mytext<- 'Text to shrink or expand'
> text_width<- 50
> pdf()
> plot(0, xlim= c(0, 100), ylim= c(0, 100))
> strwidth(mytext, units= 'user', cex= 1)   ## Too small
> #[1] 33.00625
> strwidth(mytext, units= 'user', cex= 2)   ## Too big
> #[1] 66.0125
> strwidth(mytext, units= 'user', cex= 1.5) ## About right
> #[1] 49.50937
> dev.off()
>
> Thanks!
> Dario
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
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



More information about the R-help mailing list