qqnorm and qqline in ggplot2

后端 未结 8 1754
隐瞒了意图╮
隐瞒了意图╮ 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:53

    The following code will give you the plot you want. The ggplot package doesn't seem to contain code for calculating the parameters of the qqline, so I don't know if it's possible to achieve such a plot in a (comprehensible) one-liner.

    qqplot.data <- function (vec) # argument: vector of numbers
    {
      # following four lines from base R's qqline()
      y <- quantile(vec[!is.na(vec)], c(0.25, 0.75))
      x <- qnorm(c(0.25, 0.75))
      slope <- diff(y)/diff(x)
      int <- y[1L] - slope * x[1L]
    
      d <- data.frame(resids = vec)
    
      ggplot(d, aes(sample = resids)) + stat_qq() + geom_abline(slope = slope, intercept = int)
    
    }
    

提交回复
热议问题