2013-04-03 305 views
1

我有一个简单数据帧:如何将图例添加到ggplot2折线图?

> 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

而且我想曲线图与年的线图上的x轴和y1和y2为两个单独的线,黑色和具有不同的行类型。我怎样才能得到一个表明y1代表“Bob”而y2代表“Susan”的传奇?

这里是我的尝试,它产生下面的图(无图例):

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

感谢您的帮助!今天是我第一天使用R!

回答

5

您应该将数据和功能melt()从库reshape2转换为长格式,例如,然后使用variableaes()定义linetype=。所以传说将自动进行。要删除图例中的名称variable,您可以添加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

+0

我怎样才能重新命名或者传说中的“变量”,或者完全删除吗?谢谢! – SEL 2013-04-03 18:42:32

+1

@Sel一种方法是添加scale_linetype(“”)。更新了我的答案。 – 2013-04-03 18:45:34