Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

r - Plotting quadratic regression line in scatterplot using Rstudio

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

  • bmi is body mass index and pbfm is "percentage body fat content"
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

question from:https://stackoverflow.com/questions/66063284/plotting-quadratic-regression-line-in-scatterplot-using-rstudio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...