【问题标题】:Add Cook's distance levels to ggplot2将库克的距离水平添加到 ggplot2
【发布时间】:2018-02-24 11:36:58
【问题描述】:

如何在this first plot 中添加显示厨师距离的红色虚线轮廓线 到 second plot 使用 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,但是不知道库克距离线的计算公式。

【问题讨论】:

  • stats中的函数cooks.distance

标签: r ggplot2 ggfortify


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多