Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom legends in ggplot2

I'm trying to create a legend which would takes custom labels and colours, alphas corresponding to highlighted regions in a annotated plot and not the data series plotted in the diagram using the code:

library(ggplot2)
data(economics)
p1 <- ggplot(data=economics, mapping=aes(x=date, y=unemploy)) +
  geom_line(size=1) +
  annotate("rect", xmin=as.Date('1970-01-01'), xmax=as.Date('1980-01-01'), ymin=-Inf, ymax=Inf, alpha=0.2, fill="red") +
  annotate("rect", xmin=as.Date('1990-01-01'), xmax=as.Date('2000-01-01'), ymin=-Inf, ymax=Inf, alpha=0.2, fill="green") +
p1

where I'd like to add a legend with labels saying '1970s', '1990s' with the corresponding colours red and green with alphas of 0.2 corresponding to the annotate elements. Is there a way of doing this?

like image 968
user2699676 Avatar asked Aug 24 '13 14:08

user2699676


1 Answers

Easiest would be to make new data frame for regions that should be annotated.

df<-data.frame(xmin=as.Date(c('1970-01-01','1990-01-01')),
               xmax=as.Date(c('1980-01-01','2000-01-01')),
               ymin=c(-Inf,-Inf),
               ymax=c(Inf,Inf),
               years=c("1970s","1990s"))

Then use geom_rect() and this new data frame to add those regions. Legend will be made automatically. With scale_fill_manual() you can change colors.

ggplot(data=economics, mapping=aes(x=date, y=unemploy)) +
  geom_line(size=1)+
  geom_rect(data=df,aes(xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax,fill=years),
                    alpha=0.2,inherit.aes=FALSE)+
  scale_fill_manual(values=c("red","green"))

enter image description here

like image 116
Didzis Elferts Avatar answered Sep 23 '22 21:09

Didzis Elferts