首页 > 解决方案 > 如何在 R 中绘制回归预测的结果

问题描述

我从 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)

预期结果: 在此处输入图像描述

标签: rregression

解决方案


数据和回归模型

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

方法(一):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")

在此处输入图像描述


方法(2):ggplot2方式

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

在此处输入图像描述


推荐阅读