Home > Enterprise >  Color regression lines in geom_smooth depending on the slope of the underlying linear models
Color regression lines in geom_smooth depending on the slope of the underlying linear models

Time:01-10

In this illustrative data:

set.seed(12)
df <- data.frame(
  Sequ = c(rep(1,7),rep(2,10),rep(3,14),rep(4,10)),
  Q = c(rep("q_pol",7), rep("q_wh",10),rep("q_pol",14),rep("q_wh",10)),
  pp = c(rnorm(7), rnorm(10,1), rnorm(14,2), rnorm(10,3))
)

there are pp observations grouped by Sequ and Q. I want to plot linare regression lines for such groupings of pp. This I can do. However, I also need to distinguish the regression lines by whether their slope is negative or positive. I can get at the slopes this way: how can the regression lines be colored accordingly?

library(dplyr)
libraryggplot2)
df %>%
  group_by(Sequ) %>%
  mutate(x = row_number()) %>%
  mutate(slope = lm(pp ~ x)$coeff[2]) %>%
  ggplot(
    aes(x = x, y = pp, color = as.character(Sequ)))  
  geom_smooth(method = "lm", se = FALSE)  
  facet_wrap(. ~ Q, scales = 'free_x')   
  theme(legend.position = "none")

enter image description here

CodePudding user response:

You could color by slope by mapping the condition slope > 0 on color. As this changes the default grouping we also have to add the group aesthetic to get a regression line for each Sequ:

library(dplyr)
library(ggplot2)

df %>%
  group_by(Sequ) %>%
  mutate(x = row_number()) %>%
  mutate(slope = lm(pp ~ x)$coeff[2]) %>%
  ggplot(aes(x = x, y = pp, color = slope > 0, group = factor(Sequ)))  
  geom_smooth(method = "lm", se = FALSE)  
  facet_wrap(. ~ Q, scales = 'free_x')   
  theme(legend.position = "none")
#> `geom_smooth()` using formula 'y ~ x'

  •  Tags:  
  • Related