2

I would like to add an expression to a legend entry without entering the legend directly (since I am looping over variables). Essentially I would like this:

d <- data.frame(x=1:10,y=1:10,f=rep(c("0–74",">=75"),each=5))
qplot(x,y,data=d,color=f)   

to output the way this does:

qplot(x,y,data=d,color=f) +
scale_colour_manual(values=1:2,breaks=c("0–74",">=75"),
labels=c(expression(0<=75), expression("">=75)))

(But actually I would like the the first entry 0<=74 to be 0-74, but I'm having trouble mixing expressions and non-expressions.)

I'm sure it's some kind of setting, but everything I've tried hasn't worked. Any ideas?

Tom
  • 4,860
  • 7
  • 43
  • 55

1 Answers1

2

I think you can do this within your loop by using parse(text=) to convert a string to the appropriate expression. So you could set scale_colour_manual with the appropriate labels by taking the character strings from your f variable and passing them in a manner something like this (some tweaking may be necessary):

scale_colour_manual(...,labels=c(parse(text=lab1),parse(text=lab2)))

Although parse doesn't like ">=75" so you'll probably want something like "''>=75".

For example:

qplot(x, y, data = d, color = f) +
  scale_colour_manual(
    values = 1:2,
    breaks = c("0–74", ">=75"),
    labels = c(parse(text = "0-74"),
               parse(text = paste("''",">=75",sep=""))))
MS Berends
  • 4,489
  • 1
  • 40
  • 53
joran
  • 169,992
  • 32
  • 429
  • 468
  • Thanks! This does work well for the case I gave. For some reason however it doesn't work in the larger more complex plot (map actually) I had hoped to use it in (the details of which I will spare you). I just keep getting the error `Error in lapply(X, FUN, ...) : 'pairlist' object cannot be coerced to type 'double'`. I suppose I'll have to figure this out sometime... – Tom Jun 09 '11 at 13:25