繁体   English   中英

lm 的 R 中的 autoplot():为什么我得到“恒定杠杆:残差与因子水平”而不是“残差与杠杆”plot?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM