qqnorm and qqline in ggplot2

后端 未结 8 1756
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 06:37

Say have a linear model LM that I want a qq plot of the residuals. Normally I would use the R base graphics:

qqnorm(residuals(LM), ylab=\"Residuals\")
qqline         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 06:49

    The standard Q-Q diagnostic for linear models plots quantiles of the standardized residuals vs. theoretical quantiles of N(0,1). @Peter's ggQQ function plots the residuals. The snippet below amends that and adds a few cosmetic changes to make the plot more like what one would get from plot(lm(...)).

    ggQQ = function(lm) {
      # extract standardized residuals from the fit
      d <- data.frame(std.resid = rstandard(lm))
      # calculate 1Q/4Q line
      y <- quantile(d$std.resid[!is.na(d$std.resid)], c(0.25, 0.75))
      x <- qnorm(c(0.25, 0.75))
      slope <- diff(y)/diff(x)
      int <- y[1L] - slope * x[1L]
    
      p <- ggplot(data=d, aes(sample=std.resid)) +
        stat_qq(shape=1, size=3) +           # open circles
        labs(title="Normal Q-Q",             # plot title
             x="Theoretical Quantiles",      # x-axis label
             y="Standardized Residuals") +   # y-axis label
        geom_abline(slope = slope, intercept = int, linetype="dashed")  # dashed reference line
      return(p)
    }
    

    Example of use:

    # sample data (y = x + N(0,1), x in [1,100])
    df <- data.frame(cbind(x=c(1:100),y=c(1:100+rnorm(100))))
    ggQQ(lm(y~x,data=df))
    

提交回复
热议问题