[英]plot regression line in R
哦,@GBR24 有很好的格式化數據。 然后我將根據我的評論詳細說明。
fit <- lm(y ~ poly(x, 3)) ## polynomial of degree 3
plot(x, y) ## scatter plot (colour: black)
x0 <- seq(min(x), max(x), length = 20) ## prediction grid
y0 <- predict.lm(fit, newdata = list(x = x0)) ## predicted values
lines(x0, y0, col = 2) ## add regression curve (colour: red)
x <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120)
y <- c(10, 18, 25, 29, 30, 28, 25, 22, 18, 15, 11, 8)
df <- data.frame(x,y)
plot(y ~ x, df)
model <- lm(y ~ x, df)
您正在嘗試將線性函數擬合到拋物線數據。 因此,您最終不會得到一條最適合的漂亮產品線。
像這樣的事情可能會奏效:
model <- lm(y ~ I(x^2), df)
plot(y ~ x, df)
lines(df$x, predict(model), col = 'blue')
雖然這不太適合,但我們可以嘗試三階或四階多項式模型:
model <- lm(y ~ I(x^3), df)
lines(df$x, predict(model), col = 'red')
model <- lm(y ~ I(x^4), df)
lines(df$x, predict(model), col = 'green')
雖然這些也不太合適。 看看哲元的答案以獲得更好的擬合函數。
x <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120)
y <- c(10, 18, 25, 29, 30, 28, 25, 22, 18, 15, 11, 8)
summary(lm(y~x))
plot(x,y)
abline(lm(y ~ x)) # black answer 1
########################
fit <- lm(y ~ poly(x, 2)) ## polynomial of degree 2
y0 <- predict.lm(fit) ## predicted values
lines(x, y0, col = 2) ## predicted poly red color
#y1 <- predict(fit, interval = "prediction")
[![#lines(x, y1\[,1\], col = 3) same as y1 green color # answer 2
#########################
w <- 1 + (x-1)^2 # with weights
wfit <- lm(y ~ poly(x,2), weights = w)
y2 <- predict(wfit, interval = "prediction")
lines(x, y2\[,1\], col = 4) # blue # answer 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.