[R] title: words in different colors?

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jan 22 00:54:17 CET 2009


Michael Friendly wrote:
> In ?title I see the
>
> plot(cars, main = "")
>  title(main = list("Stopping Distance versus Speed", cex=1.5, col="red", 
> font=3))
>
> I can't seem to generalize this to use several colors in a single title. 
> What I'd like is
> in latex-ish
>
> \red{Hair color} \black{ and } \blue{Eye color}
>
> to serve also as an implicit legend for points that are plotted.
>
>   

I don't know a direct way, but you could put things together by using 
strwidth() on each piece, then plotting them at the appropriate position 
using mtext.  For example:

technicolorTitle <- function(words, colours, cex=1) {
    widths <- strwidth(words,cex=cex)
    spaces <- rep(strwidth(" ",cex=cex), length(widths)-1)
    middle <- mean(par("usr")[1:2])
    total <- sum(widths) + sum(spaces)
    start <- c(0,cumsum(widths[-length(widths)] + spaces))
    start <- start + middle - total/2
    mtext(words, 3, 1, at=start, adj=0, col=colours,cex=cex)
    }

plot(1)
technicolorTitle(c("Hair color", "and", "Eye color"), c("red", "black", 
"blue"))

(I didn't duplicate title()'s choice of position and font exactly, so 
you might want to tweak this a bit.)

Duncan Murdoch




More information about the R-help mailing list