Home > Enterprise >  Is there a way to plot regressed out data?
Is there a way to plot regressed out data?

Time:11-26

I have a model:

lm(Y ~ A B X) where A B are covariates.

I have plotted the raw data using:

ggplot(data = data, aes(x=X, y=Y)   geom_point()   geom_smooth(method = "lm", se= FALSE)

I would like to plot the data such that the A B covariates have been regressed out. Is there a way to do this?

CodePudding user response:

Here is an example with one covariate. I leave it to you as an exercise to create a nice visualization with two covariates. I would probably use facets to illustrate this for different (constant) values of the second covariate.

fit <- lm(mpg ~ I(1/hp)   wt, data = mtcars) 
summary(fit)

newdata <- expand.grid(hp = seq(50, 350, by = 1),
                       wt = 2:5)
newdata$mpg <- predict(fit, newdata = newdata)

library(ggplot2)
ggplot(mtcars, aes(x = hp, y = mpg, color = wt))  
  geom_point()  
  geom_line(data = newdata, aes(group = wt))

resulting plot

  • Related