How to update ggplot legend label with plotmath

Viewed 193

I am trying to update ggplot legend labels to use plotmath, however, when I do this it separates the previously combined legends into two. It's probably easier to see with an example:

# test data and the default plot gives the correct colours and linetypes 
# in the legend but the labels are not parsed (as have not tried to yet!)

test = data.frame(x = 1:10, y = 1:10, grp=factor(rep(c("g1", "g2"),each=5)))

ggplot(test, aes(y=y, x=x, linetype=grp, colour=grp)) +
  geom_line()  

What I would like is to retain the legend keys as they are for the above plot but to change the legend labels. I have tried the following which now parse the plotmath but separate the legend keys.

ggplot(test, aes(y=y, x=x, linetype=grp, colour=grp)) +
  geom_line() + 
  scale_linetype_discrete(breaks=c("g1", "g2"), labels = parse(text=c("g[1]", "g[2]"))) +
  scale_colour_discrete(breaks=c("g1", "g2"), labels = parse(text=c("g[1]", "g[2]"))) 


# same as before
ggplot(test, aes(y=y, x=x, linetype=grp, colour=grp)) +
  geom_line() + 
  scale_linetype_manual(values=1:2, breaks=c("g1", "g2"), labels = parse(text=c("g[1]", "g[2]"))) +
  scale_colour_manual(values=1:2, breaks=c("g1", "g2"), labels = parse(text=c("g[1]", "g[2]"))) 

How can I keep the keys for the basic plot but update the labels with plotmath please (without changing the raw data)?

enter image description here

1 Answers

That works with labels = c(~g[1],~g[2]):

ggplot(test, aes(y=y, x=x, linetype=grp, colour=grp)) +
  geom_line() + 
  scale_linetype_discrete(breaks=c("g1", "g2"), 
                          labels = c(~g[1],~g[2])) + 
  scale_colour_discrete(breaks=c("g1", "g2"),
                        labels = c(~g[1],~g[2]))
Related