如何在R中绘制回归预测的结果

时间:2018-12-14 04:16:41

标签: r regression

我从R中的ML开始,我真的很喜欢可视化计算结果的想法,我想知道如何绘制预测。

library("faraway")
library(tibble)
library(stats)

data("sat")
df<-sat[complete.cases(sat),]

mod_sat_sal <- lm(total ~ salary, data = df)
new_teacher <- tibble(salary = 40)
predict(mod_sat_sal, new_teacher)

预期结果: enter image description here

1 个答案:

答案 0 :(得分:0)

数据和回归模型

data(sat, package = "faraway")
df <- sat[complete.cases(sat), ]
model <- lm(total ~ salary, data = df)

方法(1):graphics方式

# Compute the confidence band
x <- seq(min(df$salary), max(df$salary), length.out = 300)
x.conf <- predict(model, data.frame(salary = x),
                  interval = 'confidence')

# Plot
plot(total ~ salary, data = df, pch = 16, xaxs = "i")
polygon(c(x, rev(x)), c(x.conf[, 2], rev(x.conf[, 3])),
        col = gray(0.5, 0.5), border = NA)
abline(model, lwd = 3, col = "darkblue")

enter image description here


方法(2):ggplot2方式

library(ggplot2)
ggplot(df, aes(x = salary, y = total)) +
  geom_point() +
  geom_smooth(method = "lm")

enter image description here