J.d*_*doe 7 plot regression r linear-regression lm
我想在 R 中绘制一条简单的回归线。我已经输入了数据,但回归线似乎不正确。有人可以帮忙吗?
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)
abline(lm(y ~ x))
Run Code Online (Sandbox Code Playgroud)
哦,@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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
您正在尝试将线性函数拟合到抛物线数据。因此,您最终不会得到一条最适合的漂亮产品线。
像这样的事情可能会奏效:
model <- lm(y ~ I(x^2), df)
plot(y ~ x, df)
lines(df$x, predict(model), col = 'blue')
Run Code Online (Sandbox Code Playgroud)
虽然这不太适合,但我们可以尝试三阶或四阶多项式模型:
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')
Run Code Online (Sandbox Code Playgroud)
虽然这些也不太合适。看看哲元的答案以获得更好的拟合函数。