简体   繁体   English

如何将图例添加到ggplot2折线图?

[英]How to add legend to ggplot2 line chart?

I have a 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 I would like to graph a line chart with year on the x-axis and y1 and y2 as two separate lines, both black and with different line types. 我想绘制一个折线图,其中x轴上的年份为y1和y2为两条单独的线,既是黑色的,又具有不同的线型。 How can I get a legend that shows that y1 represents "Bob" and y2 represents "Susan"? 如何获得说明y1代表“鲍勃”而y2代表“苏珊”的图例?

Here is my attempt, which produces the following graph (without a 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))

在此处输入图片说明

Thank you for any help! 感谢您的任何帮助! Today is my first day using R! 今天是我使用R的第一天!

You should convert your data to long format for example with function melt() from library reshape2 and then use variable to define linetype= in aes() . 您应该将数据转换为长格式,例如使用reshape2库中的函数melt() ,然后使用variableaes()定义reshape2 linetype= So legend will be made automatically. 因此,图例将自动生成。 To remove name variable in legend you can add scale_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("")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM