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?
Easiest would be to make new data frame for regions that should be annotated.
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.