简体   繁体   中英

Add legend to geom_line() graph in r

I've been trying to add legend to my ggplot, but failed miserably. I tried the function scale_colour_manual()<\/code> , but the legend doesn't show up.

ggplot()+
geom_line(data=Summary,aes(y=Y1,x= X),colour="darkblue",size=1 )+
geom_line(data=Summary,aes(y=Y2,x= X),colour="red",size=1  )

ggplot needs aes to make a legend, moving colour inside aes(...) will build a legend automatically. then we can adjust the labels-colors pairing via scale_color_manual :

ggplot()+
  geom_line(data=Summary,aes(y=Y1,x= X,colour="Y1"),size=1 )+
  geom_line(data=Summary,aes(y=Y2,x= X,colour="Y2"),size=1) +
  scale_color_manual(name = "Y series", values = c("Y1" = "darkblue", "Y2" = "red"))

在此处输入图片说明

As has been said, a color must be specified inside an aesthetic in order for there to be a legend. However, the color inside the aesthetic is actually just a label that then carries through to other layers. Setting custom colors can be done with scale_color_manual and the legend label can be fixed with labs .

ggplot(data=Summary)+
  geom_line(mapping=aes(y=Y1,x= X,color="Y1"),size=1 ) +
  geom_line(mapping=aes(y=Y2,x= X,color="Y2"),size=1) +
  scale_color_manual(values = c(
    'Y1' = 'darkblue',
    'Y2' = 'red')) +
  labs(color = 'Y series')

To provide a more compact answer which only uses a single geom call:

ggplot2 really likes long data (key-value pairs) better than wide (many columns). This requires you to transform your data prior to plotting it using a package like tidyr or reshape2 . This way you can have a variable denoting color, inside your aes call, which will produce the legend.

For your data:

library(tidyr)
library(ggplot2)

plot_data <- gather(data, variable, value, -x)

ggplot(plot_data, aes(x = x, y = value, color = variable)) +
  geom_line() +
  scale_color_manual(values = c("firebrick", "dodgerblue")) 

You can then customize the legend via scale_color series of helpers.

I have the same problem and tries these methods but got no response. Do you know what the problem is:

P<-ggplot(data=file11, aes(x = No.)) + 
  geom_line(aes(y = S1), colour="red",size=.6)+
  geom_line(aes(y = S2), colour="magenta", alpha=.4)+
  xlab("age")+ylab("gender")+
  theme(legend.position="bottom")+
  labs(title="group 1")+ theme_bw()+theme(plot.title=element_text(size=12,hjust=0.5,face="bold"))+
  coord_flip()+ theme(aspect.ratio = 1)+ scale_x_reverse()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ theme(legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))+ylim(0.2,.6)+ scale_color_manual(values = c("S1" = "red",
    "S2" = "magenta"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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