Remi
Remi

Reputation: 1111

R plot confidence interval with lm and leveragePlots

I m using R lm() function to make a multiple linear regression

lmfit <- lm(formula = `Var1` ~
          `Var2`
        + `Var3`
        + `Var4`,
        data=df)

Then the leveragePlots function from car library

library(car)
leveragePlots(lmfit)

This gives me plots with linear regression for each Var but I haven't find a way to display the confidence interval. Can you please help?

The plot I got with leveragePlot

Upvotes: 0

Views: 1043

Answers (1)

realrbird
realrbird

Reputation: 171

This will probably seem like a very round about way of doing what you want as I don't know how to do it in leveragePlots() but here I used ggplot2 which provides a lot of flexibility. You will need all of these packages installed which you can do with install.packages(c('ggplot2', 'magrittr', 'gridExtra', 'purrr')). I use the mtcars dataset in this example because it comes built in with R. So you can run this code as is and see what is happening. Just replace the mtcars and my variables with yours, and you should get what you want.

# Load packages
library(ggplot2)
library(magrittr)
library(gridExtra)
library(purrr)

# provide the data, x variable, y variable and this function will
# create a scatterplot with a linear model fit
create_plots <- function(df, xvar, yvar) {
  if (!is.character(xvar) | !is.character(yvar)) {
    stop('xvar and yvar must but characters/strings')
  }

  plot <- df %>% 
            ggplot(aes_string(x = xvar, y = yvar)) + 
            geom_point() +
            geom_smooth(method = 'lm', se = T)
  plot
}

# map over all the variables for which you would like to create plots
graphs <- purrr::map(c('disp', 'wt'), create_plots, df = mtcars,
                     yvar = 'hp')
first_plot <- graphs[[1]] # save the results in variables
second_plot <- graphs[[2]]

grid.arrange(first_plot, second_plot) # combine the plots

Upvotes: 1

Related Questions