Combine related legends into one in ggplot2

Usually ggplot2 will automatically combine the legends for color, shape, fill and other aesthetics into one. So this is will not always be a problem.

library(ggplot2)

a <- rep(1:5,each=2)
b <- rep(c(“Before”,”After”),5)
c <- rnorm(10)
df <- data.frame(a,b,c)
colnames(df) <- c(“Subject”,”Exposure”,”Value”)
head(df)

p3 <- ggplot(data=df,aes(x=factor(Subject),y=Value)) +
geom_point(aes(shape=Exposure,fill=Exposure)) +
scale_shape_manual(values=c(Before=21,After=24)) +
scale_fill_manual(values=c(Before=”red”, After=”blue”))
p3

automated combined lengend

 

 

However, when modification was made to one of the aesthetic, the combined lenged will be split.

p4 <- ggplot(data=df,aes(x=factor(Subject),y=Value)) +
geom_point(aes(shape=Exposure,fill=Exposure)) +
scale_shape_manual(values=c(Before=21,After=24)) +
scale_fill_manual(“changed lengend”,values=c(Before=”red”, After=”blue”))
p4

split lengend

 

 

To avoid splitting the combined legend, we need to modify all the related aesthetics at the same time.

p5 <- ggplot(data=df,aes(x=factor(Subject),y=Value)) +
geom_point(aes(shape=Exposure,fill=Exposure)) +
scale_shape_manual(“changed lengend”,values=c(Before=21,After=24),labels=c(Before=”Before Exposure”,After=”After Exposure”)) +
scale_fill_manual(“changed lengend”,values=c(Before=”red”, After=”blue”),labels=c(Before=”Before Exposure”,After=”After Exposure”))
p5

non-split lengend

Leave a comment