-1

I'm having problems adding a legend to this ggplot2 plot

enter image description here

ggplot(PeriodNaive2, aes(x=log(V2), y=log(V1))) + 
   geom_line(data = PeriodNaive2, color = "red", size = 1.35) +
   geom_line(data = PeriodSmart2, color = "steelblue", size = 1.35)+labs(x = "" , y="")+
   theme(panel.background = element_rect(fill = "white", color = "black", size = 0),panel.grid = element_line(color="grey"))

I wanted to add a simple legend on the right side stating that the red graph is "PeriodNaive" and the blue one is "PeriodSmart".

I tried using "color=Legend" in the aes part of geom_line and using many other methods but it just won't work

thanks to anyone in advance for the help

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

0

Try this:

ggplot(PeriodNaive2, aes(x=log(V2), y=log(V1))) + 
   geom_line(aes(color = "PeriodNaive"), size = 1.35) +
   geom_line(data = PeriodSmart2, aes(color = "PariodSmart"), size = 1.35)+labs(x = "" , y="") +
   scale_colour_manual(values = c(PeriodNaive = "red", PeriodSmart = "steelblue")) +
   theme(panel.background = element_rect(fill = "white", color = "black", size = 0),panel.grid = element_line(color="grey"))

Legends are automatically added when mapped using aes(.) on color, fill, linetype, etc, so by moving our color= assignments into aes(.), that should happen.

r2evans
  • 141,215
  • 6
  • 77
  • 149