如何手动将图例添加到 ggplot?- R [英] How to add legend to ggplot manually? - R

查看:42
本文介绍了如何手动将图例添加到 ggplot?- R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情节:

我用来生成这个图的代码是:

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

  • 我无法共享我正在使用的数据,所以我只是在寻找一种手动添加图例的通用方法.

推荐答案

ggplot 真的只喜欢为具有美学映射的事物绘制图例.如果您设置代码名称"对于颜色,您可以在该属性的手动比例中定义它们.例如

ggplot really only likes to draw legends for things that have aesthetic mappings. If you set "code names" for colors, you can define them in a manual scale for that attribute. For example

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=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 didn't provide any data at all). Anytime you ask a question, it's just polite to include a reproducible example so the answer-er doesn't have to do all the work themselves to test.

这篇关于如何手动将图例添加到 ggplot?- R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆