r - How to add legend to ggplot2 line chart? -


i have simple dataframe:

> ih   year    y1    y2 1 2005  4.50  4.92 2 2006  4.89  6.21 3 2007  6.63  6.68 4 2008  4.89  4.60 5 2009 16.56 15.16 6 2010 17.98 17.73 7 2011 25.92 19.85

and graph line chart year on x-axis , y1 , y2 2 separate lines, both black , different line types. how can legend shows y1 represents "bob" , y2 represents "susan"?

here attempt, produces following graph (without legend):

ggplot(ih, aes(x = year)) + geom_line(aes(y=y1), linetype="dashed") +    geom_line(aes(y=y2)) +    labs(x="year", y="percentage", fill="data") +    geom_point(aes(y=y1)) +    geom_point(aes(y=y2)) 

enter image description here

thank help! today first day using r!

you should convert data long format example function melt() library reshape2 , use variable define linetype= in aes(). legend made automatically. remove name variable in legend can add scale_linetype("").

library(reshape2) ih.long<-melt(ih, id.vars="year")  ih.long    year variable value 1  2005       y1  4.50 2  2006       y1  4.89 3  2007       y1  6.63 4  2008       y1  4.89 5  2009       y1 16.56 6  2010       y1 17.98 ....  ggplot(ih.long,aes(year,value,linetype=variable))+geom_line()+geom_point()+     scale_linetype("") 

enter image description here


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -