【问题标题】:R plot confidence interval with lm and leveragePlotsR用lm和leveragePlots绘制置信区间
【发布时间】:2018-01-24 00:51:10
【问题描述】:

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

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

然后是car library中的leverPlots函数

library(car)
leveragePlots(lmfit)

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

【问题讨论】:

    标签: r linear-regression


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 2014-09-03
      • 2021-12-01
      • 2021-12-21
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      相关资源
      最近更新 更多