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

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

问题描述

我有以下情节:





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

  ggplot(df,aes(x = instance,y = total_hits))+ 
geom_point(size = 1)+
geom_line()+
geom_line(aes(x = df $ instance,y = $ line $),color =red)+
geom_vline(xintercept = 805)+
geom_line(aes(x = df $ instance,y = line2),color =blue)+
geom_line(aes(x = df $ instance,y = line3),color =purple)

我想为此图添加一个图例来标记每一行。但是,由于我手动添加每行,我不知道如何添加图例。任何提示/建议?




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


解决方案

ggplot 为具有审美映射的事物绘制传说。如果您为颜色设置了代码名称,则可以按照该属性的手动比例来定义它们。例如

  ggplot(df,aes(x = instance,y = total_hits))+ geom_point(size = 1)+ geom_line ()+ 
geom_line(aes(x = instance,y = line1,color =myline1))+
geom_vline(xintercept = 805)+ geom_line(aes(x = df $ instance,y = line2,color =myline2))+
geom_line(aes(x = instance,y = line3,color =myline3))+
scale_colour_manual(name =Line Color,
值= c(myline1 =红,myline2 =蓝,myline3 =紫))

应该有效(未经测试,因为您根本没有提供任何数据)。无论何时你问一个问题,包括一个可重现的例子<一个>所以答案 - 呃不必自己做所有的工作来测试。


I have the following plot:

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?

  • I cannot share the data I am using, so I am just looking for a general way to add legends manually.

解决方案

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=df$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天全站免登陆