Single legend when using group, linetype and colou

2019-01-26 09:11发布

问题:

I am creating a very simple plot that groups data and uses the grouping variable to determine linestyle and colour. I then override those using 'scale_linetype_manaul' and 'scale_colour_manual'. So far so good, but when I try to modify legend labels or its title, the legend splits into two parts: one for linetype and one for colour. I just want one legend, but with the custom labels and title.

Following this question, I made sure to name both scale objects the same, but that doesn't appear to 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 yields the following figure with two legends. How can I recombine those legends again, with custom labels and a title?

回答1:

This might 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"))

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