rr-marginaleffects

Using `marginaleffects::plot_comparisons()` with only one explanatory factor variable


Say I have a linear model with only one explanatory variable which is categorical:

linmod <- lm(mpg ~ factor(cyl), data = mtcars)
parameters::parameters(linmod)
#> Parameter   | Coefficient |   SE |          95% CI | t(29) |      p
#> -------------------------------------------------------------------
#> (Intercept) |       26.66 | 0.97 | [ 24.68, 28.65] | 27.44 | < .001
#> cyl [6]     |       -6.92 | 1.56 | [-10.11, -3.73] | -4.44 | < .001
#> cyl [8]     |      -11.56 | 1.30 | [-14.22, -8.91] | -8.90 | < .001

How can I use marginaleffects::plot_comparisons() to create a plot of the contrasts (6 vs. 4 and 8 vs. 4) similar to what

parameters::parameters(linmod, drop = "(Intercept)") |> plot()

does (but rotated). It seems that the function requires either a by or condition argument which isn't relevant here.


Solution

  • Unfortunately, plot_comparisons() is designed for the case with more than 1 predictor. Thankfully, all marginaleffects functions return a standard data frame, which means it is trivial to plot the results you want:

    library(marginaleffects)
    library(ggplot2)
    mod = lm(mpg ~ factor(cyl), mtcars)
    cmp = avg_comparisons(mod)
    
    
    ggplot(cmp, aes(
      y = contrast, 
      x = estimate, 
      xmin = conf.low, 
      xmax = conf.high)) +
      geom_pointrange()