在同一图例中绘制颜色和线型

时间:2018-03-05 03:16:50

标签: r ggplot2

我正在尝试绘制一组线条,一些线条我想要有虚线,有些线条我想要有不同的颜色。每一行都有线型和颜色的组合。

然而,当我在ggplot2中设置linetypecolor时,我会打印两个图例。

如何获得一组图例,图例中的每个条目都包含有关线型和颜色的信息?

例如,对于下面的例子,我希望图例中有4个条目,每条红色实线一条,红色虚线,蓝色实线和蓝色虚线。

library(ggplot2)
ggplot(mtcars) + 
  geom_line(aes(y = disp, x = mpg, color = as.factor(vs),
                linetype = as.factor(am)))

DON' T 想要的输出示例;只想要一个传奇盒 I want one legend instead of two

1 个答案:

答案 0 :(得分:1)

一种解决方案是根据vsam的互动创建新变量。这给出了4个值:(0,0),(1,0),(0,1)和(1,1)。然后,您可以手动指定颜色。并且线图不适合这里的数据;使用点。

library(tidyverse)
mtcars %>% 
  mutate(vs_am = interaction(vs, am)) %>% 
  ggplot(aes(mpg, disp)) + 
    geom_point(aes(color = vs_am, shape = vs_am)) + 
    scale_color_manual(values = c("red", "blue", "red", "blue"))

enter image description here

如果你真的想要线条,我会用geom_smooth添加一个最适合的线条#34;每组使用线性回归的线:

mtcars %>% 
  mutate(vs_am = interaction(vs, am)) %>% 
  ggplot(aes(mpg, disp)) + 
    geom_point(aes(color = vs_am, shape = vs_am)) + 
    scale_color_manual(values = c("red", "blue", "red", "blue")) + 
    geom_smooth(method = "lm", aes(group = vs_am, color = vs_am))

enter image description here