I need to use sub/superscripts in legend labels. However, if I use the label parameter of the respective scales, the colour and the fill scale are not combined anymore.
Is there a way to fix this or a different way to use sub/superscripts in legends?
DF <- data.frame(x=1:10,y=(1:10)^2,
ymax=(1:10)^2.2,
ymin=(1:10)^1.8,
fac=rep(c("a","b"),each=5))
library(ggplot2)
p <- ggplot(DF,aes(x=x,y=y,ymin=ymin,ymax=ymax,colour=fac,fill=fac)) +
geom_line() +
geom_ribbon(alpha=0.5)
print(p)

p + scale_color_discrete(labels=c("a"=expression(a[{foo}]),
"b"=expression(b[{bar}]))) +
scale_fill_discrete(labels=c("a"=expression(a[{foo}]),
"b"=expression(b[{bar}])))

Not so elegant solution is to remove fill legend and then use override.aes= within guides() function for color= legend. For this legend we can set our own fill= values. Only problem is that you have to know color names. I think this would be easier with scale_color_manual() because you already provide your own color values.
p + scale_color_discrete(labels=c("a"=expression(a[{foo}]),
"b"=expression(b[{bar}]))) +
scale_fill_discrete(guide="none")+
guides(color=guide_legend(override.aes=list(fill=c("#F8766D","#00BFC4"))))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With