Translating a group of geom_abline(s) in ggplot

Hello. First time posting. I used geom_abline() to plot a family of lines created with random slopes and intercepts. They make a bowtie pattern with the "knot" on the y-intercept. I would like to translate the "knot" to be at x = mean(var_1) instead of on x=0 so that the intercept a represents the expected value of var_2 when var_1 is at its mean. This should be easy but I can't seem to think of a simple way to do it. If I was working with the full formula for a line it would just be y = b(x - mean(var_1)) + a, but with ablines you only provide a,b and the x's are provided from the x-axis so I don't know how to manipulate them. Perhaps I'm using the wrong geom? Thank you in advance for any help.

set.seed(1237)
n <- 30
mean_of_var_1 = 37

a <- rnorm(n, 37, 1)
b <- rnorm(n, 0, .6)  

test_tbl <- tibble(
  a_intercept = a,
  b_slope = b)

test_tbl %>% ggplot() + 
   geom_abline(intercept =  a,
               slope     =  b) +
  ylim(c(0,100)) +
  xlim(c(0,100)) +
  labs(
    x = "var_1",
    y = "var_2"
  )

this is equivalent to y = bx + (a - b * mean(var_1)) so I guess you could use the same code but change the intercept ?

set.seed(1237)
library(ggplot2)
n <- 30
mean_of_var_1 = 37

a <- rnorm(n, 37, 1)
b <- rnorm(n, 0, .6)  

test_tbl <- tibble::tibble(
  a_intercept = a,
  b_slope = b)

ggplot(test_tbl) + 
  geom_abline(intercept =  a - b*mean_of_var_1,
              slope     =  b) +
  ylim(c(0,100)) +
  xlim(c(0,100)) +
  labs(
    x = "var_1",
    y = "var_2"
  )

Created on 2019-12-09 by the reprex package (v0.3.0)

Is this what you want ?

Also, know that ggplot2::stat_function allows you to plot function
https://ggplot2.tidyverse.org/reference/stat_function.html

1 Like

Thank you cderv! This is what I needed - as I thought, I was missing the forest for the trees.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.