Combine legend in ggplot2

I have a graph with several geom_point and one stat_function in ggplot2 . Is there a way to show one legend?

 df <- data.frame("x"=c(1:5), "a"=c(1,2,3,3,3), "b"=c(1,1.1,1.3,1.5,1.5)) df <- melt(df, "x") p <- ggplot(df, aes(x=x, y=value)) + geom_point(aes(colour=variable, shape=variable)) + stat_function(aes(colour="log2(x)"), fun=log2) 

enter image description here

I want to have one legend with a blue line and two color shapes. I tried

 scale_colour_discrete(name="legend", breaks=c("a", "b", "log2(x)")) + scale_shape_discrete(name="legend", breaks=c("a", "b")) 

but it does not work. Is there a way to do this automatically or manually?

Thanks in advance.

+5
source share
2 answers

Probably a simpler alternative is to use override.aes as follows:

 ggplot(df, aes(x = x, y = value)) + geom_point(aes(colour = variable, shape = variable), size = 3) + stat_function(aes(colour = "log2(x)"), fun = log2, size = 1.5) + guides(shape = FALSE, colour = guide_legend(override.aes = list(shape = c(16, 17, NA), linetype = c("blank", "blank", "solid")))) 

that leads to:

enter image description here

+5
source

Indicate . as a shape symbol for your curve and an empty string for your points:

 p <- ggplot(df, aes(x=x, y=value)) + geom_point(aes(colour=variable, shape=variable, linetype = variable), size = 3) + stat_function(aes(colour="log2(x)", shape = "log2(x)", linetype = "log2(x)"), fun=log2) + scale_shape_manual(values = setNames(c(16, 17, 46), c("a", "b", "log2(x)"))) + scale_linetype_manual(values = setNames(c(0, 0, 1), c("a", "b", "log2(x)"))) print(p) 

final schedule

+3
source

Source: https://habr.com/ru/post/1234119/


All Articles