[R] italics letter in roman string

Marc Schwartz marc_schwartz at comcast.net
Sun Mar 18 04:30:32 CET 2007


On Sat, 2007-03-17 at 21:56 -0500, Marc Schwartz wrote:
> On Sat, 2007-03-17 at 22:01 -0400, Chabot Denis wrote:
> > Hi,
> > 
> > As part of the legend to a plot, I need to have the "n" in italics  
> > because it is a requirement of the journal I aim to publish in:
> > "This study, n = 3293"
> > 
> > Presently I have:
> > legend(20, 105, "This study, n = 3293", pch=1,  col=rgb(0,0,0,0.5),
> >                  pt.cex=0.3, cex=0.8, bty="n")
> > 
> > I suppose I could leave a blank in place of the "n", then issue a  
> > text call where I'd use font=3 for a single letter, "n". But it will  
> > be tricky to find the exact location to use.
> > 
> > Is there a way to switch to font=3 just for one letter within a string?
> > 
> > Thanks in advance,
> > 
> > Denis Chabot
> 
> Denis,
> 
> Try something like this:
> 
> plot(20, 100)
> 
> leg <- legend(20, 105, "This study,    = 3293", pch = 1, 
>               col=rgb(0,0,0,0.5), pt.cex = 0.3, cex = 0.8, 
>               bty = "n")
> 
> text(leg$text$x + strwidth("This study, ", cex = 0.8), 
>      leg$text$y, "n", font = 3, cex = 0.8, adj = c(0, 0.5))
> 
> 
> Note that legend returns a list structure, which contains the x and y
> coordinates of the start of the text strings that are plotted. So I get
> that information for your line of text.
> 
> Next, I use strwidth() to calculate, in user coordinates, the length of
> the characters preceding the 'n', including spaces.  We add that
> distance to the x coordinate returned in the legend call.
> 
> I also use the 'adj' argument in the text() call, so that it is in synch
> with the same parameters in legend() for alignment with the other
> letters.
> 
> See ?strwidth for more information.
> 
> You may have to tweak the horizontal spacing of the 'n' a bit, depending
> upon the rest of your graph.

Denis,

I thought of another approach, using plotmath.

First, create a text expression, specifying that the 'n' should be
italicized. Then use that expression in the legend() call.

txt <- expression(paste("This study, ", italic(n), " = 3293"))
 
plot(20, 100)

legend(20, 105, txt, pch = 1, col=rgb(0,0,0,0.5), 
       pt.cex = 0.3, cex = 0.8, bty = "n")


That's easier that the first solution.  See ?plotmath

HTH,

Marc Schwartz



More information about the R-help mailing list