Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add legend to geom_line() graph in r

I've been trying to add legend to my ggplot, but failed miserably. I tried the function scale_colour_manual(), but the legend doesn't show up.

ggplot()+ geom_line(data=Summary,aes(y=Y1,x= X),colour="darkblue",size=1 )+ geom_line(data=Summary,aes(y=Y2,x= X),colour="red",size=1  ) 

My dataframe 'Summary' is as follows:

  X           Y1           Y2 139 1.465477e+16 7.173075e+15 277 1.044803e+16 9.275002e+15 415 1.059258e+16 8.562518e+15 553 1.033283e+16 8.268984e+15 691 9.548019e+15 1.022248e+16 830 1.008212e+16 8.641891e+15 968 9.822061e+15 9.315856e+15 1106 9.948143e+15 9.178694e+15 1244 1.013922e+16 8.825904e+15 1382 9.815094e+15 9.283662e+15 

Please advise me how to plot Y1, Y2 against X on the same graph and add a legend on the side.

like image 490
ausworli Avatar asked Nov 27 '16 20:11

ausworli


People also ask

How do I add a legend to a plot in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do you add a legend to multiple lines in R?

Adding Legends There is no direct way in R to add legends in case of multiple lines like in Excel and other scripting languages. So, to add legends we need to distribute the lines into multiple groups on the basis of coloring.

Why doesn't my Ggplot have a legend?

If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.


1 Answers

ggplot needs aes to make a legend, moving colour inside aes(...) will build a legend automatically. then we can adjust the labels-colors pairing via scale_color_manual:

ggplot()+   geom_line(data=Summary,aes(y=Y1,x= X,colour="Y1"),size=1 )+   geom_line(data=Summary,aes(y=Y2,x= X,colour="Y2"),size=1) +   scale_color_manual(name = "Y series", values = c("Y1" = "darkblue", "Y2" = "red")) 

enter image description here

like image 121
Nate Avatar answered Sep 20 '22 14:09

Nate