Big_Neezy
Big_Neezy

Reputation: 23

Plotting quadratic regression line in scatterplot using Rstudio

I'm trying to plot a quadratic regression line in a scatterplot using the following code:

mod3 <- lm(pbfm ~ bmi + I(bmi^2))

par(mfrow = c(1,1))

plot(bmi, pbfm)

lines(bmi, predict(mod3),col="blue",lwd=0.02)

The result I get is: enter image description here

Upvotes: 0

Views: 825

Answers (1)

StupidWolf
StupidWolf

Reputation: 46978

To not see the "spiderweb", sort your x-values before putting them to a line. Below I used order to get the order of the x-values, should work if there are no NAs in your x and y variables:

set.seed(111)
bmi <- runif(1000,1,50)
pbfm <- 1.5*bmi + 0.05*bmi^2 +rnorm(1000,0,30)

mod3 <- lm(pbfm ~ bmi + I(bmi^2))
plot(bmi, pbfm,cex=0.3)
o <- order(bmi)
lines(bmi[o], predict(mod3)[o],col="blue")

enter image description here

Upvotes: 1

Related Questions