向ggplot2添加图例 [英] add legend to ggplot2

查看:1979
本文介绍了向ggplot2添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在我的ggplot中添加图例,但失败了.我确实经历了其他与手动添加图例有关的问题,例如 1 2 但无法将答案应用于我的ggplot.我尝试了功能 scale_colour_manual,但图例未显示.

I've been trying to add legend to my ggplot but failed miserably. I did go through other asks which were related to adding legends manually such as 1,2 but couldn't apply the answerson my ggplot. I tried the function scale_colour_manual but the legend doesn't show up.

任何帮助将不胜感激.

Any help would be much appreciated.

p <- ggplot() +

     # corine plot
geom_point(data=t, aes(x=FPR, y=TPR),colour="black", size =3,pch=1) + 
geom_line(data=t, aes(x=FPR, y=TPR),
        colour="lightblue", size=1) +
     #globecover plot
geom_point(data=tgl, aes(x=FPR, y=TPR),colour="black",size=3,pch=1) + 
geom_line(data=tgl, aes(x=FPR, y=TPR),
        colour="red", size=1)+
#grump plot
geom_point(data=tgr, aes(x=FPR, y=TPR),colour="black",size=3, pch=1) + 
geom_line(data=tgr, aes(x=FPR, y=TPR),
        colour="pink", size=1)

p <- p+geom_abline(intercept=0, slope=1)

p<- p+ labs(list(title = "FPR vs TPR", x = "False Positive Rate", y = "True Positive Rate"))

p <-p+theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))

p+ scale_colour_manual(name="legend", value =c("corine"= "lightblue", "globcover"="red", "grump"="pink"))

是的,我的数据ttgrtgl看起来像这样:

yes, my datas t,tgr,tgl look like this:

ID   Countries   FPR       TPR
1     Bristol 0.08716076 0.6894999     
2     Brussel 0.18621056 0.8065292     
3     Budapest 0.07085285 0.8234692     
4     Edinburgh 0.05507682 0.6944172    
5     Gozo 0.11037915 0.6360882     

以此类推.

推荐答案

我编写了一个解决方案,该方法首先合并您的数据,因为它效率更高.如果每个几何图形都相同,则也不需要为每个几何图形设置aes.

I have written a solution with combining your data first, as it's much more efficient. You also don't need to set aes for each geom if they're all the same.

合并数据:

#add group variable (called data because t is a funtio)
tt$group <- "corine"
#make up the other dataframes
set.seed(1)
tgl <- data.frame(ID=1:5, Countries=LETTERS[1:5],FPR=runif(5,0,0.12),TPR=runif(5,0.5,0.8))
tgl$group <- "globcover"
tgr <- data.frame(ID=1:5, Countries=LETTERS[1:5],FPR=runif(5,0,0.12),TPR=runif(5,0.5,0.8))
tgr$group <- "grump"

#combine
all_data <- rbind(tt,tgl,tgr)

然后绘制组合数据

p2 <- ggplot(all_data, aes(x=FPR, y=TPR, group=group)) +
  geom_point(color="black") + #no need for x and y, as unchanged
  geom_line(aes(color=group)) +
  scale_colour_manual(values =c("corine"= "lightblue", "globcover"="red", "grump"="pink")) 
p2

这篇关于向ggplot2添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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