gpt4 book ai didi

r - 将库克的距离级别添加到 ggplot2

转载 作者:行者123 更新时间:2023-12-02 02:26:55 26 4
gpt4 key购买 nike

如何添加显示 this first plot 中厨师距离的红色虚线轮廓线 this first plotsecond plot使用 ggplot 和 ggfortify 吗?

second plot

使用的代码:

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

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

最佳答案

经过一番研究,我设法使用公式 sqrt(level * length(coef(model)) * (1 - lever)/leverage) 绘制了 level 的轮廓 code>,这是 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))

residuals vs leverage plot with cook's distance contours

关于r - 将库克的距离级别添加到 ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com