Search code examples
rggplot2quadratic-curve

What is the best way to add 1000 regression lines to a ggplot? (Model-based bootstrapping)


From a bootstrapping model I have 1000 sets of coefficients for this regression model:

y = b0 + b1x + b2(x^2)

What is the function call to plot a quadratic line if I already have the coefficients? I.E. I do not want to "fit" a linear model to my data.

I tried adding lines via a for loop to my ggplot object:

for (i in 1:1000) { 
  reg_line <- stat_function(fun=function(x) quad$coefficients[1] + 
                                      quad$coefficients[i,2]*x + quad$coefficients[i,3]*(x**2))
  reg_lines <- reg_lines + reg_line}

That didn't work - it seems to only add the last line in the loop.

The reason I want to add 1000 regression lines to my plot is because it is for a homework problem - I am well aware this is not a common use case.


Solution

  • There may be other ways to do this, but hopefully this can give you some ideas. I used the mtcars dataset and generated some bootstrap samples for modelling. You can skip this step.

    library(ggplot2)
    library(tidyr)
    library(dplyr)
    
    data(mtcars)
    
    drat=seq(min(mtcars$drat), max(mtcars$drat), length.out=100)
    
    # Bootstrap function
    bs <- function() {
      df = mtcars[sample(1:nrow(mtcars), replace=TRUE),]
      lm_fit <- lm(mpg ~ drat+I(drat^2), data=df)
      data.frame(Model=predict(lm_fit, newdata=data.frame(drat))) # Replace with your own
    }
    
    foo <- replicate(10, bs()) # Simulate
    

    You would start from here since you should already have a data frame or list of predicted values from your 1,000 bootstrap models. Reshape it into a very long form to create a grouping column for the geom_line function.


    foo_long <- data.frame(foo, drat) %>%
      pivot_longer(cols=-drat, names_to="Model", values_to="mpg")
    
    ggplot(data = mtcars, aes(x = drat, y = mpg)) + 
      geom_point(color='blue') +
      geom_line(data = foo_long, aes(x=drat, y=mpg, group=Model, color=Model)) +
      guides(color=FALSE)
    

    enter image description here