Dr. Fabian Habersack
Dr. Fabian Habersack

Reputation: 1141

Visualizing marginal effect of two-way interaction of binary logistic model in ggplot

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!

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

And I'm claiming (and actually finding) that there region mediates the effect of a given motive on voting for party XY.

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...

Upvotes: 0

Views: 1794

Answers (1)

Daniel
Daniel

Reputation: 7832

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()

enter image description here

Note that the dataset I used is labelled, that's why the axes are annotated with "proper" value and variable labels.

Upvotes: 3

Related Questions