A single legend when using a group, such as line and color in ggplot2?

I am creating a very simple graph that groups data and uses a grouping variable to determine linestyle and color. Then I redefine those used by "scale_linetype_manaul" and "scale_colour_manual". So far, everything is fine, but when I try to change the legend's legend or its name, the legend is divided into two parts: one for the line type and one for the color. I just want one legend, but with custom labels and title.

Following this question , I definitely called both scalable objects the same, but this does not help.

Minimal example:

X <- data.frame(TPP=factor(c(1,5,10,1,5,10,1,5,10)), value=c(-0.035819, 0.003356, 0.066091, -0.028039, 0.004333, 0.060292, -0.023115, 0.005661, 0.058821), horizon=c(1,1,1,2,2,2,3,3,3)) ggplot(X, aes(x=horizon, y=value, group=TPP, col=TPP, linetype=TPP))+ geom_line(size=1)+ scale_linetype_manual(name="X", values = c("solid","dashed", "dotted")) + scale_color_manual(name="X", values = c("black", "red", "blue"), labels=c("Low", "5","High")) 

This gives the following figure with two legends. How can I combine these legends with custom labels and title again?

+8
colors r ggplot2 line legend
source share
1 answer

This can help:

  ggplot(X, aes(x=horizon, y=value, group=TPP, col=TPP, linetype=TPP))+geom_line(size=1)+ scale_linetype_manual(name="X", values = c("solid","dashed", "dotted"),labels=c("Low", "5","High")) + scale_color_manual(name ="X", values = c("black", "red", "blue"),labels=c("Low", "5","High")) 

enter image description here

If the labels defined in scale_color_manual and scale_linetype_manual are different, or if they are specified in only one of them, you will get two different legends.

+13
source share

All Articles