ggplot2中使用组,线型和颜色时的单个图例? [英] Single legend when using group, linetype and colour in ggplot2?

查看:155
本文介绍了ggplot2中使用组,线型和颜色时的单个图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个非常简单的分组数据,并使用分组变量来确定线条样式和颜色。然后我重写那些使用'scale_linetype_manaul'和'scale_colour_manual'。到目前为止很好,但是当我尝试修改图例标签或标题时,图例分为两部分:一个用于线型,一个用于颜色。我只想要一个传说,但是有自定义标签和标题。



如果在 scale_color_manual scale_linetype_manual 中定义的标签不同,或者仅在其中的一个中指定它们,您将获得两个不同的传说。


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?

解决方案

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.

这篇关于ggplot2中使用组,线型和颜色时的单个图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆