phantom text in graphics

 The title function allows you to change the color of the text using the col argument, but that color is applied to the entire text string -- there's no obvious way to set the color of individual words.

Or is there?  Barry Rowlingson offers an elegant solution that uses the "overhead transparency" principle of R graphics: you can overlay additional graphical elements one atop another, to build up your graph layer by layer.  So you could add the title Hair color in red on the left, and Eye color in blue on the right, and put a black "and" in the middle.  The trick is in the positioning -- it could take a lot of trial and error to get the x position of each element correct.  But if you plot the same text three times in three different colors, but leave some words blank (so they won't overlay previously plotted elements) you don't have to worry about positioning at all.  The phantom notation allows you to do that, as shown in Barry's solution:

plot(rnorm(20),rnorm(20),col=rep(c("red","blue"),c(10,10)))

title(expression("Hair color" * 
  phantom(" and Eye color")),col.main="red")

title(expression(phantom("Hair color and ") * 
  "Eye color"),col.main="blue")

title(expression(phantom("Hair color ") *

  "and " phantom("Eye color"),col.main="black")) 

Colortitle

The phantom notation means "leave room for this, but don't draw it" -- see help(plotmath) for other examples. Barry also provides a function multiTitle to create multicolor titles in a single command:

multiTitle(color="red","Hair color"color="black",

  " and ",color="blue","Eye color")


Another solution (suggested by Duncan Murdoch) is to use the strwidth function to calculate the widths of words and use this information to set the x position of individual words, as demonstrated in his technicolorTitle function. However, as this solution is implemented using the mtext function the results can be slightly different to what title usually produces.

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04