简体   繁体   English

将图例添加到 ggplot2

[英]add legend to ggplot2

I've been trying to add legend to my ggplot but failed miserably.我一直试图在我的 ggplot 中添加图例,但失败了。 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.我确实通过了其他与手动添加图例相关的问题,例如1 , 2但无法应用我的 ggplot 的答案。 I tried the function scale_colour_manual but the legend doesn't show up.我尝试了函数scale_colour_manual但图例没有出现。

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"))

yes, my datas t , tgr , tgl look like this:是的,我的数据ttgrtgl看起来像这样:

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     

and so forth.等等。

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.如果它们都相同,您也不需要为每个 geom 设置aes

Combining data:合并数据:

#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)

An then plot the combined data然后绘制组合数据

make the plot制作情节

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

在此处输入图片说明

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

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