How to set different colours for the lines representing different group membership in geom_smooth

80 Views Asked by At

My group variables (group_var) has two levels. I have produced a scatterplot with "Y" = blue and "N" = red. Since I have a lot of points, if I don't set a colour for the line in the geom_smooth argument, it's hard to pick out the two lines (one red and blue) from the cloud of red and blue points.

To make them more visible, I've tried colouring the lines black in the code below. However, now you can't tell which line is for the "Y" group and which is for the "N" group.

data %>% ggplot(aes(ind_var ,dep_var, color = group_var)) + geom_point(alpha = 0.5, size = 2) + geom_smooth(aes(group=group_var), method = "lm", color = "black", size = 0.5)

Is there a way to set the colours for the two lines to be different? E.g. "Y" to be a dark blue and "N" to be a dark red. I have only found resources on how to change the colour of both lines and not how to set each line's colour separately.

1

There are 1 best solutions below

3
stefan On

There are multiple options to achieve your desired result, e.g. you could make use of the fill aes for the points which would allow to specify different colors for the lines. Another option which I proceed below is to increase the number of categories mapped on color, i.e. instead of group_var I map paste(group_var, "line", sep = "_") on the color aes inside geom_smooth. This way we have different categories for the lines and the points for which we could set different colors.

Of course does this approach duplicate the number of legend entries and depending on your desired result needs some additional tweaking of the legend.

Using some fake example data based on iris:

library(dplyr, warn = FALSE)
library(ggplot2)

data <- iris |>
  select(ind_var = Petal.Length, dep_var = Petal.Width, group_var = Species)

data %>%
  ggplot(aes(ind_var, dep_var, color = group_var)) +
  geom_point(alpha = 0.5, size = 2) +
  geom_smooth(
    aes(
      group = group_var,
      color = paste(group_var, "line", sep = "_")
    ),
    method = "lm",
    size = 0.5
  ) +
  scale_colour_manual(
    values = c(
      "lightblue", "darkblue",
      "tomato", "firebrick",
      "lightgreen", "darkgreen"
    )
  )
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.
#> `geom_smooth()` using formula = 'y ~ x'