[R] multiple colors within same line of text

Jim Lemon jim at bitwrit.com.au
Sat Aug 18 13:15:34 CEST 2007


Andrew Yee wrote:
> Hi, I'm interested in using mtext(), but with the option of having multiple
> colors in the same line of text.
> 
> For example, creating a line of text where:
> 
> Red is red and blue is blue
> 
> How do you create a text argument that lets you do this within mtext()?
> 
You can do something like this with "text" and then use xpd=TRUE to use 
it outside the plot. I think it would be more fiddly trying to use "mtext".

concat.text<-function(x,y,txt,col) {
  thisx<-x
  for(txtstr in 1:length(txt)) {
   text(thisx,y,txt[txtstr],col=col[txtstr],adj=0)
   thisx<-thisx+strwidth(txt[txtstr])
  }
}
plot(0,xlim=c(0,1),ylim=c(0,1),type="n")
ctext<-c("Roses are ","red, ","violets are ","purple")
concat.text(0,0.5,ctext,col=c("black","red","black","purple"))

Jim



More information about the R-help mailing list