R绘图置信区间与lm和leveragePlots

时间:2018-01-23 15:19:29

标签: r linear-regression

我使用R lm()函数进行多元线性回归

base64_encoded

然后来自汽车图书馆的leveragePlots功能

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

这给了我每个Var的线性回归图,但我还没有找到显示置信区间的方法。你能帮忙吗?

The plot I got with leveragePlot

1 个答案:

答案 0 :(得分:1)

这可能看起来像是一个非常圆的方式来做你想要的,因为我不知道如何在leveragePlots()中做到这一点,但在这里我使用ggplot2提供了很大的灵活性。您将需要安装所有这些软件包,您可以使用install.packages(c('ggplot2', 'magrittr', 'gridExtra', 'purrr'))。我在这个例子中使用了mtcars数据集,因为它是用R内置的。所以你可以按原样运行这个代码,看看发生了什么。只需将mtcars和我的变量替换为您的变量,就可以得到您想要的结果。

# 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