将 Cook 的距离级别添加到 ggplot2
Add Cook's distance levels to ggplot2
如何在 this first plot 中添加显示厨师距离的红色虚线轮廓线
到 second plot 使用 ggplot
和 ggfortify
?
使用的代码:
library(ggfortify)
model <- glm(mpg ~ wt, data = mtcars, family = gaussian())
plot(model, which = 5) # first plot
autoplot(model, which = 5) # second plot
我认为可以添加 geom_contour
,但我不知道用于计算 Cook 距离线的公式。
经过一些研究,我设法使用公式 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))
如何在 this first plot 中添加显示厨师距离的红色虚线轮廓线
ggplot
和 ggfortify
?
使用的代码:
library(ggfortify)
model <- glm(mpg ~ wt, data = mtcars, family = gaussian())
plot(model, which = 5) # first plot
autoplot(model, which = 5) # second plot
我认为可以添加 geom_contour
,但我不知道用于计算 Cook 距离线的公式。
经过一些研究,我设法使用公式 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))