在R中绘制回归线

时间:2016-09-28 01:56:49

标签: r plot regression 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))

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:3)

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)

enter image description here

您正尝试将线性函数拟合为抛物线数据。因此,你不会最终得到一个最合适的线条。

这样的事可能有用:

model <- lm(y ~ I(x^2), df)

plot(y ~ x, df)
lines(df$x, predict(model), col = 'blue')

enter image description here

虽然这不太合适,但我们可以尝试三阶或四阶多项式模型:

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')

enter image description here

虽然那些也不太合适。看看哲源的答案是否有更好的功能。

答案 1 :(得分:3)

哦,@ 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)

enter image description here

答案 2 :(得分:0)

  1. 正如我在原始问题中的图形上方所说,切换了x轴和y轴
  2. 线性模型答案最适合该问题,因为这就是要问的问题。
  3. 其他答案还涉及其他建模选择,例如上方的最佳三次方模型或下方的最佳二次方模型。这只是结合了上面的推理。
    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

original data dots,black linear abline, red quadratic curve, blue weighted curve

相关问题