1

I'd like to add a legend to a ggplot graph and I have not found a similar answer online.

My legend needs to indicate the vertical lines are dates that major events happened and what the other colours represent (eg. smoothed line is a moving average). The vertical lines do not form part of the dataset.

RePrEx:

library(data.table)
library(ggplot2)
library(lubridate)
dat <- as.data.table(x=1:10)
dat$V1 <- as.Date(dat$V1,origin = "2000-01-01")
dat$y_a = c(2,3,4,2,4,2,5,5,4,3)
dat$y_b = c(4,5,5,6,4,3,4,5,6,5)

sections <- as.Date(c(3,5,8),origin = "2000-01-01")

ggplot(data=dat)+
  geom_line(aes(x=V1,y=y_a),colour="black")+
  geom_smooth(aes(x=V1,y=y_a),alpha=0,colour="blue")+
  geom_vline(xintercept = sections,linetype="dashed",colour="red")+
  geom_vline(xintercept = as.Date(7,origin = "2000-01-01"),colour="darkgreen")+
  xlab("Time")+
  ylab("Height")

My example graph is in the link.

Current Output

It is not possible to explain these graph details elsewhere.

MrFlick
  • 195,160
  • 17
  • 277
  • 295

1 Answers1

2

If you want something in your legend, it needs to be mapped via aes(). This means moving some of the vline stuff into a data.frame so you can map it.

ggplot(data=dat)+
  geom_line(aes(x=V1,y=y_a), colour="black")+
  geom_smooth(aes(x=V1,y=y_a, colour="blue"),alpha=0)+
  geom_vline(aes(colour="darkgreen", xintercept = xint), data=data.frame(xint=as.Date(7,origin = "2000-01-01")), key_glyph  = "path")+
  geom_vline(aes(colour="red", xintercept = xint), linetype="dashed", data=data.frame(xint=sections), key_glyph  = "path") +
  xlab("Time")+
  ylab("Height") + 
  scale_color_manual(values = c("blue","red","darkgreen"), 
                     breaks = c("blue","red","darkgreen"),
                     labels = c("Moving","Major","Important"))

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295