qqnorm and qqline in ggplot2

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

    With the latest ggplot2 version (>=3.0), new function stat_qq_line is implemented (https://github.com/tidyverse/ggplot2/blob/master/NEWS.md) and a qq line for model residuals can be added with:

    library(ggplot2)
    model <- lm(mpg ~ wt, data=mtcars)
    ggplot(model, aes(sample = rstandard(model))) + geom_qq() + stat_qq_line()
    

    rstandard(model) is needed to get the standardized residual. (credit @jlhoward and @qwr)

    If you get an 'Error in stat_qq_line() : could not find function "stat_qq_line"', your ggplot2 version is too old and you can fix it by upgrading your ggplot2 package: install.packages("ggplot2") .

提交回复
热议问题