我想使用ggplot来复制用“效果”包获得的图部分效果(部分残差)。为此,我需要检索一些信息。 这是我想用ggplot复制的情节。
library(effects)
mod <- lm(log(prestige) ~ income:type + education, data=Prestige)
eff = effect("education", mod, partial.residuals=T)
plot(eff)
从eff
对象我能够检索到部分残差,如eff$residuals
,但它们不足以复制图。我认为我需要的是残差和边际预测效应。但是我无法从eff
对象中检索它们。
否则,我只有残差分数无法根据边际效应线绘制。
有关如何检索此信息的任何提示?
答案 0 :(得分:2)
您几乎掌握了所有可用信息。这需要花费更多时间来概括,但是这里的一些代码会产生与effects
包大致类似的数字。请注意,更顺畅的是关闭,但我没有费心去挖掘原因。
代码应该是自我解释的。我只复制了the package中的closest
函数。
mod <- lm(log(prestige) ~ income:type + education, data=Prestige)
eff = effect("education", mod, partial.residuals=T)
library(ggplot2)
library(gridExtra)
closest <- function(x, x0) apply(outer(x, x0, FUN=function(x, x0) abs(x - x0)), 1, which.min)
x.fit <- unlist(eff$x.all)
trans <- I
x <- data.frame(lower = eff$lower, upper = eff$upper, fit = eff$fit, education = eff$x$education)
xy <- data.frame(x = x.fit, y = x$fit[closest(trans(x.fit), x$education)] + eff$residuals)
g <- ggplot(x, aes(x = education, y = fit)) +
theme_bw() +
geom_line(size = 1) +
geom_point(data = xy, aes(x = x, y = y), shape = 1, col = "blue", size = 2) +
geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.5) +
geom_smooth(data = xy, aes(x = trans(x), y = y),
method = "loess", span = 2/3, linetype = "dashed", se = FALSE)
grid.arrange(plot(eff), g, ncol = 2)