0

I have a list with several lm formulas:

y ~ I(x^0.5), y ~ I(log(x)), ...)

I'm looking for a way to plot each one with ggplot2, any ideas on how to do that? (same data, only formulas change).

Example:

Formulas <- list("y = a + bx" = as.formula("mpg ~ disp"),
                 "y = a + bx^0.5" = as.formula("mpg ~I(disp^0.5)"),
                 "y = a + b(logx)" = as.formula("mpg ~I(log(disp))"),
                 "y = a + b(logx)^0.5" = as.formula("mpg ~I(log(disp)^0.5)"))

models <- lapply(Formulas, lm, data = mtcars)
Artur Guerra
  • 75
  • 2
  • 8
  • 4
    Please, make a reproducible example. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – bbiasi May 15 '19 at 00:51
  • do you want all slopes on the same plot or different plots for each slope? also, does each model only have a single predictor? – andrew_reece May 15 '19 at 01:22
  • different plots for each formula (doesnt mind having multiple ggplot graphics, because I'm gonna export with R Markdown later). Yes, each model only have a single predictor. – Artur Guerra May 15 '19 at 01:35

1 Answers1

3

Here is the general idea to do it with map...

library(tidyverse)

models = list(y ~ I(x^0.5), y ~ I(log(x)))

tibble(x=1:100) %>% 
  mutate(y=log(x) + rnorm(n(), 0, 0.1)) %>% 
  ggplot(aes(x=x, y=y)) + 
    geom_point() + 
    map(models, ~ geom_smooth(method='lm', formula=.))

enter image description here

John Colby
  • 22,169
  • 4
  • 57
  • 69
  • Tried to do this with my reproducible example, like this: ggplot(mtcars,aes(x=mtcars$mpg, y=mtcars$disp)) + geom_point() + map(models, ~ geom_smooth(method='lm', formula=.)) . But I get: 2: Computation failed in `stat_smooth()`: object 'disp' not found – Artur Guerra May 15 '19 at 01:45