【问题标题】:How do I plot just the residuals in plotly or ggplot2?如何仅在 plotly 或 ggplot2 中绘制残差?
【发布时间】:2020-12-02 06:21:01
【问题描述】:
如果我只想绘制残差,我可以这样做
plot(model$residuals)
我会得到一个漂亮的散点图。我如何在 ggplot2 或 plotly 中做同样的事情?
我不想绘制残差与拟合值。
谢谢,
阿迪
【问题讨论】:
标签:
r
ggplot2
plot
plotly
linear-regression
【解决方案1】:
大概是这样的?
model <- lm(Sepal.Width ~ Petal.Length, data = iris)
ggplot(data.frame(x = seq(model$residuals), y = model$residuals)) +
geom_point(aes(x, y)) +
labs(x = "Index", y = "Residuals",
title = paste("Residuals of", format(model$call)))
这比:
plot(model$residuals)
【解决方案2】:
与@AllanCameron 类似,您可以使用broom 包,它还提供有关模型结果的其他选项(df 中的变量):
library(ggplot2)
library(broom)
#Data
data("iris")
#Model
m1 <- lm(Sepal.Length~Sepal.Width,data=iris)
df <- augment(m1)
ggplot(df, aes(x = 1:nrow(df), y = .resid)) + geom_point() + xlab('x')