Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine fill and colour legends when using expression labels

Tags:

r

ggplot2

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)

enter image description here

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}]))) 

enter image description here

like image 590
Roland Avatar asked Jun 06 '13 12:06

Roland


1 Answers

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"))))

enter image description here

like image 165
Didzis Elferts Avatar answered Nov 03 '22 22:11

Didzis Elferts