19

I have the following plot:

Plot

The code I used to generate this plot was:

ggplot(df, aes(x = instance, y = total_hits))+
geom_point(size = 1)+
geom_line()+
geom_line(aes(x=df$instance, y = line1), colour="red")+
geom_vline(xintercept=805) +
geom_line(aes(x=df$instance, y = line2), colour="blue")+
geom_line(aes(x=df$instance, y = line3), colour="purple") 

I would like to add a legend to this plot, to label each line. However, since I added each line manually, I am not sure how to add the legend. Any tips/advice?

  • I cannot share the data I am using, so I am just looking for a general way to add legends manually.
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
user3749549
  • 379
  • 2
  • 3
  • 8
  • 2
    Since you can't share your plot, could you make your example reproducible by either (a) using a built-in data set or (b) simulating a little illustrative example? It saves everyone who might try to answer your question from having to do it themselves and gets everyone on the same page. – Gregor Thomas Jun 30 '14 at 18:58

1 Answers1

49

ggplot really only likes to draw legends for things that have aesthetic mappings. If you set "code names" for colors, you can define them in a manual scale for that attribute. For example

ggplot(df, aes(x = instance, y = total_hits)) +
  geom_point(size = 1) + 
  geom_line()+
  geom_line(aes(x=instance, y = line1, colour="myline1")) +
  geom_vline(xintercept=805) + 
  geom_line(aes(x=instance, y = line2, colour="myline2"))+
  geom_line(aes(x=instance, y = line3, colour="myline3")) +
  scale_colour_manual(name="Line Color",
      values=c(myline1="red", myline2="blue", myline3="purple"))

should work (untested since you didn't provide any data at all). Anytime you ask a question, it's just polite to include a reproducible example so the answer-er doesn't have to do all the work themselves to test.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 6
    salient point being: move that `colour="red"` statement from outside the `aes()` parentheses to inside them for each geom. – Brian D Dec 01 '16 at 14:58
  • 1
    @BrianD Wrong, first, there is no `colour="red"` statement in the example, second, if you mean `colour="myline1"`, it should be inside `aes()`. – Meow Apr 06 '17 at 03:01
  • 1
    @meow My comment was referring to OP's example. I agree with the above answer. And yes, the colour= statements should be inside the aes(). – Brian D Apr 06 '17 at 03:21