[R] text colour in legend

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Nov 5 21:50:15 CET 2004


On Fri, 2004-11-05 at 12:57, Marcus Leinweber wrote:
> hello,
> 
> 
> the following example gives a plot with a legend:
> 
> 
> plot(-10:10,-10:10,type="n")
> x=1:10
> y=1:10
> tt=c("A","B","C","D","E","F")
> text(x,y,tt,cex=.8)
> legend(-10,10,paste(tt," ",x,y),text.col=c(2:4))  # each row in different  
> colour
> 
> but how can I colour the legend text by "column" meaning tt in red, x in  
> blue and y in green?
> 
> thanks for your help.
> 
> marcus


This is possible, using a bit of a trick with legend(). Instead of
printing each row in sequence, we print each column in sequence:

x <- 1:10
y <- 1:10
tt <- LETTERS[1:10]

plot(x, y, pch = tt)

# Now use legend. Modify the vector of
# text items here so that each set of 10
# elements are in sequence. Modify the color
# argument to be a sequence of 10 of each color
# set the 'ncol' argument to 3

legend(1, 10, c(tt, x, y), 
       text.col = rep(2:4, each = 10), 
       ncol = 3) 


HTH,

Marc Schwartz




More information about the R-help mailing list