1

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.

4
  • + geom_abline(slope = , intercept = )? Commented Mar 3, 2020 at 9:45
  • @Hugh how do I add the quadratic term to geom_abline? Commented Mar 3, 2020 at 9:48
  • Sorry. Too glib. You won't be able to use geom_abline for quadratic, but are you able to use it to add 1000 straight lines on to your plot, or does it too only add the last one? To get a better response you should probalbly include a minimal reproducible example so that when we run your code we get the same result. Right now you've only given an excerpt. Commented Mar 3, 2020 at 9:53
  • Maybe this (the second answer): stackoverflow.com/questions/15633714/… Commented Mar 3, 2020 at 9:54

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your detailed answer. I think this is the way to do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.