首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ggplot绘制通过效果库获得的部分效果

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

Stack Overflow用户
提问于 2017-05-13 15:31:00
回答 1查看 2.4K关注 0票数 0

我想使用ggplot来复制绘图的部分效果(带有部分残差),就像使用"effect“包获得的一样。为此,我需要检索一些信息。这是我想用ggplot复制的图。

代码语言:javascript
复制
library(effects)    
mod <- lm(log(prestige) ~ income:type + education, data=Prestige)
eff = effect("education", mod, partial.residuals=T)

plot(eff)

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

有什么关于如何检索此信息的提示吗?

EN

回答 1

Stack Overflow用户

发布于 2017-05-13 19:50:21

您几乎拥有所有可用的信息。这将需要更多的时间来推广,但这里有一些代码,它们产生的图形与effects包中的图形大致相同。请注意,平滑器已关闭,但我没有费心去找出原因。

代码应该是自解释的。我只从the package复制了函数closest

代码语言:javascript
复制
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)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43950459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档