add legend to ggplot2

2019-07-14 01:30发布

问题:

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

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     

and so forth.

回答1:

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.

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



标签: r ggplot2 legend