How to add legend to ggplot manually? - R

I have the following graph:

Plot

The code I used to create this graph 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 indicate each line. However, since I added each line manually, I am not sure how to add a legend. Any tips / advice?

  • I cannot share the data that I use, so I'm just looking for a general way to add legends manually.
+6
source share
1 answer

ggplot really loves to draw legends only for things that have aesthetic correspondences. If you specify "code names" for colors, you can define them on a manual scale for this attribute. for instance

 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=df$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 haven't provided any data at all). Each time you ask a question, it is simply polite to include a reproducible example , so the answering machine does not have to do all the work on its own for testing.

+19
source

Source: https://habr.com/ru/post/971560/


All Articles