The*_*aya 5 plot interaction r ggplot2 glm
我想在GLM上添加拟合函数ggplot
.默认情况下,它会自动创建带有交互的图.我想知道,如果我能从模型中绘制拟合函数而不进行交互.例如,
dta <- read.csv("http://www.ats.ucla.edu/stat/data/poisson_sim.csv")
dta <- within(dta, {
prog <- factor(prog, levels=1:3, labels=c("General", "Academic", "Vocational"))
id <- factor(id)
})
plt <- ggplot(dta, aes(math, num_awards, col = prog)) +
geom_point(size = 2) +
geom_smooth(method = "glm", , se = F,
method.args = list(family = "poisson"))
print(plt)
Run Code Online (Sandbox Code Playgroud)
但是,我想要模型中的情节,
`num_awards` = ß0 + ß1*`math` + ß2*`prog` + error
Run Code Online (Sandbox Code Playgroud)
我试着这样做,
mod <- glm(num_awards ~ math + prog, data = dta, family = "poisson")
fun.gen <- function(awd) exp(mod$coef[1] + mod$coef[2] * awd)
fun.acd <- function(awd) exp(mod$coef[1] + mod$coef[2] * awd + mod$coef[3])
fun.voc <- function(awd) exp(mod$coef[1] + mod$coef[2] * awd + mod$coef[4])
ggplot(dta, aes(math, num_awards, col = prog)) +
geom_point() +
stat_function(fun = fun.gen, col = "red") +
stat_function(fun = fun.acd, col = "green") +
stat_function(fun = fun.voc, col = "blue") +
geom_smooth(method = "glm", se = F,
method.args = list(family = "poisson"), linetype = "dashed")
Run Code Online (Sandbox Code Playgroud)
ggplot
有效地执行此操作有简单的方法吗?
Ben 绘制特定模型项的响应预测值的想法启发了我改进函数type = "y.pc"
的选项sjp.glm
。GitHub 上有新的更新,版本号为 1.9.4-3。
现在,您可以绘制特定项的预测值,其中一个沿 x 轴使用,第二个用作分组因子:
sjp.glm(mod, type = "y.pc", vars = c("math", "prog"))
Run Code Online (Sandbox Code Playgroud)
这给你以下情节:
如果您的模型有两个以上项,则需要该参数vars
来指定 x 轴范围的项和分组的项。
您还可以对组进行分面:
sjp.glm(mod, type = "y.pc", vars = c("math", "prog"), show.ci = T, facet.grid = T)
Run Code Online (Sandbox Code Playgroud)
据我所知,没有办法欺骗你geom_smooth()
这样做,但你可以做得比你现在做得更好一点。您仍然需要自己拟合模型并添加线条,但您可以使用该predict()
方法生成预测并将其加载到与原始数据结构相同的数据框中......
mod <- glm(num_awards ~ math + prog, data = dta, family = "poisson")
## generate prediction frame
pframe <- with(dta,
expand.grid(math=seq(min(math),max(math),length=51),
prog=levels(prog)))
## add predicted values (on response scale) to prediction frame
pframe$num_awards <- predict(mod,newdata=pframe,type="response")
ggplot(dta, aes(math, num_awards, col = prog)) +
geom_point() +
geom_smooth(method = "glm", se = FALSE,
method.args = list(family = "poisson"), linetype = "dashed")+
geom_line(data=pframe) ## use prediction data here
## (inherits aesthetics etc. from main ggplot call)
Run Code Online (Sandbox Code Playgroud)
(这里唯一的区别是,我的预测跨越了所有组的整个水平范围,就像您fullrange=TRUE
在 中指定的一样geom_smooth()
)。
原则上,似乎sjPlot 包应该能够处理这类事情,但看起来用于执行此绘图类型的相关代码位是硬编码的,以假设二项式 GLM ...哦,好吧。