使用ggplot绘制效果库获得的部分效果

时间:2017-05-13 07:31:00

标签: r plot ggplot2 partial effects

我想使用ggplot来复制用“效果”包获得的图部分效果(部分残差)。为此,我需要检索一些信息。 这是我想用ggplot复制的情节。

library(effects)    
mod <- lm(log(prestige) ~ income:type + education, data=Prestige)
eff = effect("education", mod, partial.residuals=T)

plot(eff)

Partial effect plot of Education Term

eff对象我能够检索到部分残差,如eff$residuals,但它们不足以复制图。我认为我需要的是残差和边际预测效应。但是我无法从eff对象中检索它们。 否则,我只有残差分数无法根据边际效应线绘制。

有关如何检索此信息的任何提示?

1 个答案:

答案 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)

enter image description here