Search code examples
rlinear-regressionemmeans

How do I plot a single numerical covariate using emmeans (or other package) from a model?


After variable selection I usually end up in a model with a numerical covariable (2nd or 3rd degree). What I want to do is to plot using emmeans package preferentially. Is there a way of doing it?

I can do it using predict:

m1 <- lm(mpg ~ poly(disp,2), data = mtcars)
df <- cbind(disp = mtcars$disp, predict.lm(m1, interval = "confidence"))
df <- as.data.frame(df)

ggplot(data = df, aes(x = disp, y = fit)) +
    geom_line() +
  geom_ribbon(aes(ymin = lwr, ymax = upr, x = disp, y = fit),alpha = 0.2)

enter image description here

I didn't figured out a way of doing it using emmip neither emtrends

For illustration purposes, how could I do it using mixed models via lme?

m1 <- lme(mpg ~ poly(disp,2), random = ~1|factor(am), data = mtcars)

Solution

  • Using sjPlot:

    plot_model(m1, terms = "disp [all]", type = "pred")

    gives the same graphic.

    Using emmeans:

    em1 <- ref_grid(m1, at = list(disp = seq(min(mtcars$disp), max(mtcars$disp), 1)))
    emmip(em1, ~disp, CIs = T)
    

    returns a graphic with a small difference in layout. An alternative is to add the result to an object and plot as the way that I want to:

    d1 <- emmip(em1, ~disp, CIs = T, plotit = F)