首页 文章

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

提问于
浏览
0

这个问题在这里已有答案:

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

但是当我在ggplot2中设置 linetypecolor 时,我会打印两个图例 .

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

例如,对于下面的内容,我希望图例中有4个条目,红色实线,红色虚线,蓝色实线和蓝色虚线各一个 .

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

Example of the output that I DON'T want; just want one legend box
I want one legend instead of two

1 回答

  • 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 为每个组使用线性回归添加"best fit"行:

    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

相关问题