Single legend when using group, linetype and colour in ggplot2?

一世执手 提交于 2019-11-28 03:31:54

问题


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.



来源:https://stackoverflow.com/questions/31610202/single-legend-when-using-group-linetype-and-colour-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!