[R] How to split a plot into vertical subregions with width proportional to length of a character string?

Jim Lemon jim at bitwrit.com.au
Thu Sep 12 01:26:18 CEST 2013


On 09/12/2013 03:51 AM, isabella at ghement.ca wrote:
>
>
> 	BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px;
> }Hello,
>
> 	I am trying to create a plot whose x-axis is wide enough to
> accommodate the following:
>
> 	a) a character string on the left side (i.e., Text 1);
>   b) a known range of values in the middle (i.e., Range);
>   c) a character string on the right side (i.e., Label 2)
>
> 	The plot would start with the range of values in the middle and would
> be expanded to the left and right by a width proportional to the
> length of Text 1 and Label 2, respectively.  (The width would need to
> be expressed in the same units as those of the middle range of
> values.)
>
> 	In R, how can I determine the width of Text 1 and Label 2 and express
> it in the same units as those pertaining to Range?  (I know how to
> determine the width of these character strings in inches for a given
> plot via strwidth(), but for some reason I am not able to connect that
> width to the units of Range.)
>
> 	Here is some R code illustrating what the plot would look like:
>   plot(NA, xlim=c(1,10), ylim=c(1,5),type="N")
>   abline(v=1,lty=2,col="red")
>   abline(v=2,lty=2,col="red")
>   abline(v=8,lty=3,col="blue")
>   abline(v=10,lty=3,col="blue")
>   text(1,3,"Text 1",pos=4)
>   text(8,3,"Label 2",pos=4)
>   arrows(2,3,8,3,code=3, length=0.1,lwd=2)
>   text(5,3,"Range",pos=3)

Hi Isabella,
Your illustration is helpful, but there are a couple of things that I 
will have to guess. The first is that you want the usual margins around 
the plot, and the second is that the outer vertical lines on your 
illustration are the "x" limits {par(usr[1:2])} of the plot. What you 
have is a fairly simple algebra problem.

xrange = stringwidth1 + xlim + stringwidth2

Using the default plotting device on my setup:

xrange = 5.76 in.
stringwidth1 = 0.457 in.
stringwidth2 = 0.551 in.

Therefore xlim must fit into:

5.76 - 1.008 = 4.75 in.

Say your xlim (in user units) is 1 to 10. This means that the xlim 
passed to the plot command must be:

10 * 5.76/4.75 = 12.13

or if you want the default .04 padding on either side:

10.08 * 5.76/4.75 = 12.23

Having discovered this, you can now plot with:

xlim<-c(1 - 2.13 * 0.457/1.008,10 + 2.13 * 0.551/1.008)
plot(1:10,1:10,xlim=xlim,xaxt="n")
axis(1,at=1:10)
text(xlim[1],5,"Text 1")
text(xlim[2],5,"Label 2",adj=1)

So in general, plot without the strings with the full x range, then 
adjust for the strings, then plot again.

You will probably want to fiddle with the padding and text adjustments.

Jim



More information about the R-help mailing list