rggplot2regressionmediangplots

ggplot graph with line above and below the median


I am trying to make a ggplot graph with two regression lines: One below and the other above the median to depict potential effect of age in the sample. So fa, I have tried: geom_hline (aes(yintercept = median(df$y) I do not get anything. I can also have two graphs, one with one line and the second one with the other line and combine them, but I haven't had success. Any help?

Yacila

geom_hline (aes(yintercept = median(df$y)

Expected a line above the mean


Solution

  • "The effect of age" sounds like age is on the x-axis. Here is a minimal example for two regression lines on either side of the median on the x-axis with tidyverse:

    library(tidyverse)
    data(mtcars)
    mtcars %>% 
      ggplot(aes(x = mpg, y = qsec)) + geom_point() +
      geom_smooth(data = filter(mtcars, mpg <= median(mpg)), method = "lm", size = 1.2, se=F) +
      geom_smooth(data = filter(mtcars, mpg > median(mpg)), method = "lm", size = 1.2, se=F) +
      geom_vline(xintercept=median(mtcars$mpg))
    

    enter image description here