![](/img/trans.png)
[英]Why R plots Residuals vs Leverage instead of Residuals vs Factor Levels (ANOVA test & model with 'aov')
[英]autoplot() in R for lm: why do I get a “Constant Leverage: Residuals vs Factor Levels” instead of a “Residuals vs Leverage” plot?
我在 R 中使用一个连续变量(DENSITY)和一个因子(SEASON)进行 ANCOVA。 当我检查 model 假设时,我得到一个名为 plot 的 plot:“恒定杠杆:残差 vs 因子水平”而不是“残差 vs 杠杆”Z32FA6E1B78A56D40284953E。
limp.mod <- lm(EGGS~DENSITY*SEASON, data=limp)
autoplot(limp.mod,smooth.colour = NA, which=5)
如何获得“残差与杠杆”plot? 为什么我的教科书中完全相同的代码给出了另一个 autoplot() output?
在此先感谢您的帮助!
如果没有可重现的示例,我将首先基于内置数据集iris
创建一个 model 。
df1 <- iris[1:100, 3:5]
df1$Species <- droplevels(df1$Species)
str(df1)
#'data.frame': 100 obs. of 3 variables:
# $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species : Factor w/ 2 levels "setosa","versicolor": 1 1 1 1 1 1 1 1 1 1 ...
fit <- lm(Petal.Length ~ Petal.Width*Species, df1)
至于 plot, autoplot
是通用的 function。 Package ggfortify
包括用于 class "lm"
等对象的方法。
从help("autoplot.lm")
:
如果需要图的子集,请指定数字 1:6 的子集。
默认值为which = c(1, 2, 3, 5)
。 尝试参数的所有 6 个值,我们看到想要的图不是其中之一。 所以需要建立一个自定义图表。
残差和杠杆值可以分别从stats::resid
stats::hatvalues
和 stats::hatvalues 获得。
library(ggplot2)
dflev <- data.frame(Leverage = hatvalues(fit), y = resid(fit))
ggplot(dflev, aes(Leverage, y)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed") +
ggtitle("Residuals vs Leverage") +
lims(y = c(-1, 1)) +
ylab("") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.