1

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

Yacila
  • 13
  • 3
  • Welcome to Stack Overflow. Please edit your question and provide the information mentioned here to improve your post: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – John Polo Mar 12 '23 at 13:24
  • Did you call `ggplot()'` first? As in `ggplot(df) + geom_hline(yintercept=median(y))` – dandrews Mar 12 '23 at 13:41
  • Are you fitting a regression line for those above the median age and another for those below the median age? – russellpierce Mar 12 '23 at 14:04
  • Please provide enough code so others can better understand or reproduce the problem. – Community Mar 12 '23 at 14:32

2 Answers2

1

Credit

goes to Marco for pointing out that

"The effect of age" sounds like age is on the x-axis.


Answer

Include a group aesthetic on the condition of age being below or above the median. This will split the data into two groups.

df1 <- iris[1:2]
names(df1) <- c("y", "age")

library(ggplot2)

ggplot(df1, aes(age, y, group = age < median(age))) +
  geom_point() +
  geom_vline(xintercept = median(df1$age)) +
  geom_smooth(method = lm, formula = y ~ x, se = FALSE)

Created on 2023-03-12 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1

"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

Marco
  • 2,368
  • 6
  • 22
  • 48