ggplot legend not displyed

2019-07-20 13:46发布

问题:

The legend is not displayed by the following code:

library(ggplot2)
g=ggplot() 
g=g+geom_line(aes(x=1:10,y=1:10),color="red",size=0.2)
g=g+geom_line(aes(x=5:12,y=15:22),color="green",size=0.2)
g=g+theme(legend.position = c(0, 1),legend.justification = c(0, 1))
g=g+scale_color_manual(values = c("red","green"))
g

I have searched all over the internet for the answer without any success. Note that I cannot use ggplot(aes(...)) or use a dataframe because the two lines have different x-coordinates.

回答1:

You need to map the colors in the aes call - right now, there's no color scale to show.

E.g., consider this

library(ggplot2)
colors <- c("L1" = "red", "L2" = "green")
g=ggplot() 
g=g+geom_line(aes(x=1:10,y=1:10, color="L1"),,size=0.2)
g=g+geom_line(aes(x=5:12,y=15:22, color="L2"),size=0.2)
g=g+theme(legend.position = c(0, 1),legend.justification = c(0, 1))
g=g+scale_color_manual(values = colors)
g



回答2:

For that, you should put color inside the aes:

library(ggplot2)
g=ggplot() 
g=g+geom_line(aes(x=1:10,y=1:10,color="red"),size=0.2)
g=g+geom_line(aes(x=5:12,y=15:22,color="green"),size=0.2)
g=g+theme(legend.position = c(0, 1),legend.justification = c(0, 1))
g 



标签: r ggplot2