Guilherme Parreira
Guilherme Parreira

Reputation: 1041

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)

Upvotes: 1

Views: 1037

Answers (2)

Guilherme Parreira
Guilherme Parreira

Reputation: 1041

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)

Upvotes: 1

Russ Lenth
Russ Lenth

Reputation: 6810

I suspect that your issue is due to the fact that by default, covariates are reduced to their means in emmeans. You can use theat or cov.reduce arguments to specify a larger number of values. See the documentation for ref_grid and vignette(“basics”, “emmeans”), or the index of vignette topics.

Upvotes: 2

Related Questions