选择线性回归线的颜色

时间:2019-05-17 03:03:32

标签: r ggplot2

如何设置线性回归线的颜色而与线颜色无关?


library(tidyverse)

df <- tibble(
  x = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6),
  y = c(1, 3, 2, 4, 1, 4, 2, 5, 3, 7, 5, 10),
  type = c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B")
)

ggplot(df, aes(x = x, y = y)) +
  geom_line(aes(colour = type), size = 4) +
  scale_x_continuous(breaks = 1:6) +
  geom_smooth(data = filter(df, x >= 3), aes(x = x, y = y, group = type), method = "lm", se = FALSE, size = 0.5) +
  scale_color_manual(values = c("A" = "dark red", "B" = "dark blue")) +
  theme_minimal()

2 个答案:

答案 0 :(得分:2)

如果您只想为两条回归线寻找一种颜色,最简单的方法是在对colour的调用中添加一个geom_smooth参数。

library(tidyverse)

df <- tibble(
  x = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6),
  y = c(1, 3, 2, 4, 1, 4, 2, 5, 3, 7, 5, 10),
  type = c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B")
)

ggplot(df, aes(x = x, y = y)) +
  geom_line(aes(colour = type), size = 4) +
  scale_x_continuous(breaks = 1:6) +
  scale_color_manual(values = c("A" = "dark red", "B" = "dark blue")) +
  geom_smooth(data = filter(df, x >= 3), aes(x = x, y = y, group = type), 
              colour = 'black', method = "lm", se = FALSE, size = 0.5) 
  theme_minimal()

如果您希望回归线具有不同的颜色,则可以镜像type变量和基于新变量的颜色,如下所示:

library(tidyverse)

df <- tibble(
  x = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6),
  y = c(1, 3, 2, 4, 1, 4, 2, 5, 3, 7, 5, 10),
  type = c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B")
)

ggplot(df, aes(x = x, y = y)) +
    geom_line(aes(colour = type), 
              size = 4) +
    # mirror the `type` variable
    geom_smooth(data = filter(df, x >= 3) %>% 
                       mutate(class = factor(ifelse(type == 'A', 0, 1))),
                # group and colour on `class` instead of `type` 
                aes(x = x, y = y, colour = class),
                method = "lm", se = FALSE, size = 2) +
    scale_colour_manual(name = 'Type',
                        values = c('A' = '#6703AA', 
                                   'B' = '#BB8901',
                                   '0' = '#FF2499',
                                   '1' = '#00BBFF'),
                        # add breaks to hide '0' and '1' in legend
                        breaks = c('A', 'B')) +
    scale_x_continuous(breaks = 1:6) +
    theme_minimal()

enter image description here

我们可能会忽略一种更简单的方法,但这是一种满足您需求的清晰有效的方法。

注意:不要忘记将我在调用中提供的颜色更改为scale_colour_manual;他们真的很恐怖。

答案 1 :(得分:1)

一种方法(有点怪)是在geom_smooth函数中指定颜色。由于要拟合一条直线,因此曲线仅需要2个点。使用ncolor选项,然后创建所需颜色的矢量

ggplot(df, aes(x = x, y = y)) +
  geom_line(aes(colour = type), size = 4) +
  scale_x_continuous(breaks = 1:6) +
  geom_smooth(data = filter(df, x >= 3), aes(x = x, y = y, group=type), method = "lm",
              se = FALSE, size = 2, n=2, col=rep(c("pink", "green"), each=2)) +
  scale_color_manual(values = c("A" = "dark red", "B" = "dark blue")) +
  theme_minimal()

enter image description here