【问题标题】:replicate multiple regression plot from excel in R从 R 中的 excel 复制多元回归图
【发布时间】:2017-01-02 16:20:20
【问题描述】:

我正在努力在 R 中重现一个在 Excel 中很容易获得的多元线性回归图。 我举个例子。假设我在 R 中有以下数据框(称为测试):

y   x1  x2  x3
2   5   5   9
6   4   2   9
4   2   6   15
7   5   10  6
7   5   10  6
5   4   3   12

为了生成线性回归,我简单地写:

reg=lm(y ~ x1 + x2 + x3, data = test)

现在我想绘制 y 变量的实际值、预测的 y 以及在辅助轴上标准化残差的图。我添加了 Excel 中的屏幕截图,以便您了解我的意思。

要访问我想获得的 Excel 图: the plot is in italian, "y" means observed y values, "Y prevista" means predicted Y values and "Residui standard" means standardized residuals. The standard residuals are plotted on a secondary axis

如果有人能告诉我谁能在 R 中实现上述目标,将不胜感激。

【问题讨论】:

    标签: r linear-regression timeserieschart


    【解决方案1】:

    使用类似的东西

    matplot(seq(nrow(test)), cbind(test$y, predict(reg), rstudent(reg)), type="l")
    

    但您必须设置坐标轴以确保一切正常

    【讨论】:

    • 非常感谢!太好了,会找出秒轴!
    【解决方案2】:

    你可以试试这样的。更容易调试您的代码。

    test <- data.frame(y=c(2,6,4,7,7,5), x1=c(5,4,2,5,5,4), x2=c(5,2,6,10,10,3), 
                      x3=c(9,9,15,6,6,12))
    
    reg=lm(y ~ x1 + x2 + x3, data = test)
    
    # Add new columns to dataframe from regression
    test$yhat <- reg$fitted.values
    test$resid <- reg$residuals
    # Create your x-variable column
    test$X <-seq(nrow(test))
    
    library(ggplot2)
    library(reshape2)
    # Columns to keep
    keep = c("y", "yhat", "resid", "X")
    
    # Drop columns not needed
    test <-test[ , keep, drop=FALSE]
    
    # Reshape for easy plotting
    test <- melt(test, id.vars="X")
    
    # Everything on the same plot
    ggplot(test, aes(X,value, col=variable)) + 
      geom_point() + 
      geom_line()
    

    对于不同的外观,您还可以将geom_line 替换为geom_smooth()

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2018-11-03
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2017-07-30
      • 1970-01-01
      相关资源
      最近更新 更多