我想使用ggplot来复制绘图的部分效果(带有部分残差),就像使用"effect“包获得的一样。为此,我需要检索一些信息。这是我想用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对象中检索它们。否则,我只有残差分数,不能根据边际效果线绘制出来。
有什么关于如何检索此信息的提示吗?
发布于 2017-05-13 19:50:21
您几乎拥有所有可用的信息。这将需要更多的时间来推广,但这里有一些代码,它们产生的图形与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)

https://stackoverflow.com/questions/43950459
复制相似问题