所以我有 2 个模型用于我正在使用的数据集:
> Bears1Fit1 <- lm(Weight ~ Neck.G)
>
> Bears2Fit2 <- lm(Weight ~ Neck.G + I(Neck.G)^2)
我想在同一个散点图上绘制这两个模型。到目前为止我有这个:
> plot(Neck.G, Weight, pch = c(1), main = "Black Bears Data: Weight Vs Neck Girth", xlab = "Neck Girth (inches) ", ylab = "Weight (pounds)")
> abline(Bears1Fit1)
但是,我不确定我应该如何将二次模型放在同一张图上。我希望能够在同一个图形上同时显示两条线。
最佳答案
以下是汽车数据集的示例:
data(cars)
制作模型:model_lm <- lm(speed ~ dist, data = cars)
model_lm2 <- lm(speed ~ dist + I(dist^2), data = cars)
制作新数据:new.data <- data.frame(dist = seq(from = min(cars$dist),
to = max(cars$dist), length.out = 200))
预测:pred_lm <- predict(model_lm, newdata = new.data)
pred_lm2 <- predict(model_lm2, newdata = new.data)
阴谋: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)
使用 ggplot2
library(ggplot2)
将所有数据放在一个数据框中并使用 melt
转换为长格式来自 reshape2
preds <- data.frame(new.data,
linear = pred_lm,
quadratic = pred_lm2)
preds <- reshape2::melt(preds,
id.vars = 1)
阴谋ggplot(data = preds)+
geom_line(aes(x = dist, y = value, color = variable ))+
geom_point(data = cars, aes(x = dist, y = speed))+
theme_bw()
编辑:另一种使用两个
geom_smooth
仅使用 ggplot2 的方法图层,默认公式为 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()
关于r - 如何在同一张图上绘制线性和二次模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615655/