如何在同一张图上绘制线性和二次模型?

tem*_*ses 4 statistics r

所以我使用的数据集有两个模型:

> Bears1Fit1 <- lm(Weight ~ Neck.G)
> 
> Bears2Fit2 <- lm(Weight ~ Neck.G + I(Neck.G)^2)
Run Code Online (Sandbox Code Playgroud)

我想在同一个散点图上绘制这两个模型。到目前为止我有这个:

> plot(Neck.G, Weight, pch = c(1), main = "Black Bears Data: Weight Vs Neck Girth", xlab = "Neck Girth (inches) ", ylab = "Weight (pounds)")
> abline(Bears1Fit1)
Run Code Online (Sandbox Code Playgroud)

但是,我不确定应该如何将二次模型放在同一张图上。我希望能够在同一个图表上显示两条线。

mis*_*use 5

这是汽车数据集的示例:

data(cars)
Run Code Online (Sandbox Code Playgroud)

制作模型:

model_lm <- lm(speed ~ dist, data = cars)
model_lm2 <- lm(speed ~ dist + I(dist^2), data = cars)
Run Code Online (Sandbox Code Playgroud)

制作新数据:

new.data <- data.frame(dist = seq(from = min(cars$dist),
                                 to = max(cars$dist), length.out = 200))
Run Code Online (Sandbox Code Playgroud)

预测:

pred_lm <- predict(model_lm, newdata = new.data)
pred_lm2 <- predict(model_lm2, newdata = new.data)
Run Code Online (Sandbox Code Playgroud)

阴谋:

plot(speed ~ dist, data = cars)
lines(pred_lm ~ new.data$dist, col = "red")
lines(pred_lm2 ~ new.data$dist, col = "blue")
legend("topleft", c("linear", "quadratic"), col = c("red", "blue"), lty = 1)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

与ggplot2

library(ggplot2)
Run Code Online (Sandbox Code Playgroud)

将所有数据放在一个数据框中,并使用meltfrom转换为长格式reshape2

preds <- data.frame(new.data,
                    linear = pred_lm,
                    quadratic =  pred_lm2)

preds <- reshape2::melt(preds,
                        id.vars = 1)
Run Code Online (Sandbox Code Playgroud)

阴谋

ggplot(data = preds)+
  geom_line(aes(x = dist, y = value, color = variable ))+
  geom_point(data = cars, aes(x = dist, y = speed))+
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:另一种方法仅使用 ggplot2 使用两层geom_smooth,一层具有默认公式y ~ x(因此不需要指定),一层具有二次模型formula = y ~ x + I(x^2)。为了获得图例,我们可以color在调用中aes指定命名所需的条目,因为我们希望它在图例中显示。

ggplot(cars,
       aes(x = dist, y = speed)) +
  geom_point() +
  geom_smooth(method = "lm",
              aes(color = "linear"),
              se = FALSE) +
  geom_smooth(method = "lm",
              formula = y ~ x + I(x^2),
              aes(color = "quadratic"),
              se = FALSE) +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述