在ggplot中可视化二进制逻辑模型的双向交互的边际效应 [英] Visualizing marginal effect of two-way interaction of binary logistic model in ggplot
问题描述
有人可以建议使用ggplot快速直观地了解glm模型/二进制logistic回归模型的双向交互吗?我对边际效应感兴趣!
Can someone suggest a quick and comprehensible way of how to visualize a two-way interaction of a glm model/ binary logistic regression model, using ggplot? I'm interested in the marginal effect!
我看了其他帖子,但并没有真正理解它们.另一个问题是由于R版本(3.4.2),我无法使用ggpredict/gginteraction.
I have looked at other posts, but did not really understand them. Another issue is that I cannot use ggpredict/ gginteraction because of by R-version (3.4.2).
我的数据结构如下所示(简化):
My data structure looks like this (simplified):
region_AB motive voter_attribute vote_for_party_XY
1 1 1 1
1 0 1 1
1 1 0 0
0 0 0 0
0 0 1 0
0 1 0 0
我声称(并实际上发现)该地区在调解给定动机对XY政党的投票产生影响.
And I'm claiming (and actually finding) that there region mediates the effect of a given motive on voting for party XY.
现在我知道这不是可复制的示例.但是也许有人可以提出一个适合所有人的解决方案(至少对于glm模型的双向交互而言).如果有必要且有帮助,也许mtcars
数据集可以用作示例目的:甚至是使用此数据集的互动条件模型的示例.
Now I know this is not a reproducible example. But maybe someone can come up with a one fits all solution (at least for the case of two-way interactions of glm models). If necessary and it helps, maybe the mtcars
dataset can serve examplary purposes: there's even an example for an interaction-term model using this dataset.
我希望有人对此有一个很好的解决方案.这可能是可视化双向交互的边际效应的一般指南...
I'm hoping someone has a nice and easy solution to this. This could be a general guide for visualizing marginal effects of two-way interactions...
推荐答案
您可以使用 ggeffects -package 来计算边际效应.返回值是一个数据帧,但是有一个plot()
方法可以创建/返回ggplot对象.这是一个带有二进制结果的人工示例,但是您可以从上面引用的网站的文章"中找到更多详细信息.
You can use the ggeffects-package to compute marginal effects. The return value is a data frame, but there's a plot()
-method that creates/returns a ggplot-object. Here'a an artificial example with binary outcome, but you can find more details in the "Articles" from the above referenced website.
library(ggeffects)
library(sjmisc) # to preserve labels
data(efc)
# prepare data, create binary outcome and make
# numeric variables categorical
efc$neg_c_7d <- dicho(efc$neg_c_7)
efc$c161sex <- to_factor(efc$c161sex)
efc$c172code <- to_factor(efc$c172code)
# fit logistic regression
m <- glm(
neg_c_7d ~ c12hour + c161sex * c172code,
data = efc,
family = binomial(link = "logit")
)
# compute and plot marginal effects
ggpredict(m, c("c172code", "c161sex")) %>% plot()
请注意,我使用的数据集已标记,这就是为什么要对轴进行注释的原因带有适当"的值和变量标签.
Note that the dataset I used is labelled, that's why the axes are annotated with "proper" value and variable labels.
这篇关于在ggplot中可视化二进制逻辑模型的双向交互的边际效应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!