5

如何使用 and 将在第一个图中显示 Cook 距离的红色虚线等高线添加到第二 这第一个情节中?ggplotggfortify

第二个情节

使用的代码:

library(ggfortify)
model <- glm(mpg ~ wt, data = mtcars, family = gaussian())
plot(model, which = 5) # first plot
autoplot(model, which = 5) # second plot

我认为geom_contour可以添加,但我不知道用于计算库克距离线的公式。

4

1 回答 1

5

经过一番研究,我设法level使用公式绘制轮廓sqrt(level * length(coef(model)) * (1 - leverage)/leverage),这是 R 用来绘制轮廓的plot.lm。不过,我使用的方法肯定可以改进。

library(ggplot2)
library(ggfortify)
model <- glm(mpg ~ wt, data = mtcars, family = gaussian())

cd_cont_pos <- function(leverage, level, model) {sqrt(level*length(coef(model))*(1-leverage)/leverage)}
cd_cont_neg <- function(leverage, level, model) {-cd_cont_pos(leverage, level, model)}

autoplot(model, which = 5) +
    stat_function(fun = cd_cont_pos, args = list(level = 0.5, model = model), xlim = c(0, 0.25), lty = 2, colour = "red") +
    stat_function(fun = cd_cont_neg, args = list(level = 0.5, model = model), xlim = c(0, 0.25), lty = 2, colour = "red") +
    scale_y_continuous(limits = c(-2, 2.5))

带有厨师距离等高线的残差与杠杆图

于 2018-02-25T18:22:18.723 回答