0

Suppose I have a dataset with outcome y, and covariates x and z, for example:

N = 100
x = rnorm(N)
z = rnorm(N)
y = 3*x + 2*z + rnorm(N)
dataset = data.frame(x=x, z=z, y=y)

For a univariate regression of y on x, I can obtain a plot with confidence interval, as follows:

ggplot(dataset) + 
   geom_point(aes(x=x, y=y)) + 
   stat_smooth(method='lm', formula = y~x)

enter image description here

QUESTION: How could I get the same plot for a multivariate regression of y on x and z, where the line corresponds to a specific value of z (say, z=0.42)?

I can draw the line as follows:

model <- lm(data=dataset, formula = y~x+z)

special_z = 0.42

ggplot() + 
   geom_point(data=dataset, aes(x=x, y=y)) + 
   geom_abline(
      slope = coef(model)["x"], 
      intercept = coef(model)["(Intercept)"] + special_z*coef(model)["z"],
      color = "blue")

enter image description here

However, how could I add the accompanying confidence interval to this line?

1
  • Using the emmeans or ggeffects packages to compute the predicted values and CIs you need might be the easiest way to get there
    – Ben Bolker
    Mar 8 at 18:20

2 Answers 2

1

The marginaleffects package can do this (and a lot more). See the vignette on plots: https://vincentarelbundock.github.io/marginaleffects/articles/plot.html

library(ggplot2)
library(marginaleffects)

N = 100
x = rnorm(N)
z = rnorm(N)
y = 3*x + 2*z + rnorm(N)
dataset = data.frame(x=x, z=z, y=y)

model <- lm(data=dataset, formula = y~x+z)

plot_predictions(model, condition = list("x", "z" = 0.42))


plot_predictions(model,
    condition = list("x", "z" = "threenum"),
    points = .3,
    rug = TRUE)


plot_predictions(model, condition = list("x", "z" = stats::fivenum)) + 
    theme_minimal() +
    scale_fill_brewer("Dark2") +
    scale_color_brewer("Dark2")

1

you can use the visreg r package, look here for more details visreg

simple_model <- lm(data=dataset, formula = y~x+z)
visreg(simple_model, "x")

model1

for models with an interaction term,The visreg package offers two methods to visualize the effect of two explanatory variables here one of them.

int_model <- lm(data=dataset, formula = y~x*z)
visreg(int_model, "x",by="z",overlay=TRUE)

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.