ggplot2中的qqnorm和qqline

时间:2010-12-05 02:28:02

标签: r ggplot2 ggproto

假设有一个线性模型LM,我想要一个残差的qq图。通常我会使用R基础图形:

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

我可以弄清楚如何获得情节的qqnorm部分,但我似乎无法管理qqline:

ggplot(LM, aes(sample=.resid)) +
    stat_qq()

我怀疑我遗漏了一些非常基本的东西,但似乎应该有一种简单的方法来做到这一点。

编辑:非常感谢下面的解决方案。我已经修改了代码(非常轻微)以从线性模型中提取信息,这样绘图就像R基础图形包中的便利图一样。

ggQQ <- function(LM) # argument: a linear model
{
    y <- quantile(LM$resid[!is.na(LM$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(LM, aes(sample=.resid)) +
        stat_qq(alpha = 0.5) +
        geom_abline(slope = slope, intercept = int, color="blue")

    return(p)
}

8 个答案:

答案 0 :(得分:50)

以下代码将为您提供所需的图表。 ggplot包似乎不包含用于计算qqline参数的代码,因此我不知道是否可以在(可理解的)单行中实现这样的情节。

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)

}

答案 1 :(得分:21)

您还可以使用此功能添加置信区间/置信区间(从car:::qqPlot复制的部分代码)

gg_qq <- function(x, distribution = "norm", ..., line.estimate = NULL, conf = 0.95,
                  labels = names(x)){
  q.function <- eval(parse(text = paste0("q", distribution)))
  d.function <- eval(parse(text = paste0("d", distribution)))
  x <- na.omit(x)
  ord <- order(x)
  n <- length(x)
  P <- ppoints(length(x))
  df <- data.frame(ord.x = x[ord], z = q.function(P, ...))

  if(is.null(line.estimate)){
    Q.x <- quantile(df$ord.x, c(0.25, 0.75))
    Q.z <- q.function(c(0.25, 0.75), ...)
    b <- diff(Q.x)/diff(Q.z)
    coef <- c(Q.x[1] - b * Q.z[1], b)
  } else {
    coef <- coef(line.estimate(ord.x ~ z))
  }

  zz <- qnorm(1 - (1 - conf)/2)
  SE <- (coef[2]/d.function(df$z)) * sqrt(P * (1 - P)/n)
  fit.value <- coef[1] + coef[2] * df$z
  df$upper <- fit.value + zz * SE
  df$lower <- fit.value - zz * SE

  if(!is.null(labels)){ 
    df$label <- ifelse(df$ord.x > df$upper | df$ord.x < df$lower, labels[ord],"")
    }

  p <- ggplot(df, aes(x=z, y=ord.x)) +
    geom_point() + 
    geom_abline(intercept = coef[1], slope = coef[2]) +
    geom_ribbon(aes(ymin = lower, ymax = upper), alpha=0.2) 
  if(!is.null(labels)) p <- p + geom_text( aes(label = label))
  print(p)
  coef
}

示例:

Animals2 <- data(Animals2, package = "robustbase")
mod.lm <- lm(log(Animals2$brain) ~ log(Animals2$body))
x <- rstudent(mod.lm)
gg_qq(x)

enter image description here

答案 2 :(得分:12)

线性模型的标准Q-Q诊断绘制了标准化残差的分位数与N(0,1)的理论分位数。 @ Peter的ggQQ函数绘制残差。下面的代码片段对此进行了修改,并添加了一些修饰内容,使得情节更像是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)
}

使用示例:

# 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))

答案 3 :(得分:12)

从版本2.0开始,ggplot2有一个记录良好的扩展接口;所以我们现在可以轻松地为qqline写一个新的统计数据(这是我第一次做的,所以改进是welcome):

qq.line <- function(data, qf, na.rm) {
    # from stackoverflow.com/a/4357932/1346276
    q.sample <- quantile(data, c(0.25, 0.75), na.rm = na.rm)
    q.theory <- qf(c(0.25, 0.75))
    slope <- diff(q.sample) / diff(q.theory)
    intercept <- q.sample[1] - slope * q.theory[1]

    list(slope = slope, intercept = intercept)
}

StatQQLine <- ggproto("StatQQLine", Stat,
    # http://docs.ggplot2.org/current/vignettes/extending-ggplot2.html
    # https://github.com/hadley/ggplot2/blob/master/R/stat-qq.r

    required_aes = c('sample'),

    compute_group = function(data, scales,
                             distribution = stats::qnorm,
                             dparams = list(),
                             na.rm = FALSE) {
        qf <- function(p) do.call(distribution, c(list(p = p), dparams))

        n <- length(data$sample)
        theoretical <- qf(stats::ppoints(n))
        qq <- qq.line(data$sample, qf = qf, na.rm = na.rm)
        line <- qq$intercept + theoretical * qq$slope

        data.frame(x = theoretical, y = line)
    } 
)

stat_qqline <- function(mapping = NULL, data = NULL, geom = "line",
                        position = "identity", ...,
                        distribution = stats::qnorm,
                        dparams = list(),
                        na.rm = FALSE,
                        show.legend = NA, 
                        inherit.aes = TRUE) {
    layer(stat = StatQQLine, data = data, mapping = mapping, geom = geom,
          position = position, show.legend = show.legend, inherit.aes = inherit.aes,
          params = list(distribution = distribution,
                        dparams = dparams,
                        na.rm = na.rm, ...))
}

这也概括了分布(与stat_qq完全相同),可以按如下方式使用:

> test.data <- data.frame(sample=rnorm(100, 10, 2)) # normal distribution
> test.data.2 <- data.frame(sample=rt(100, df=2))   # t distribution
> ggplot(test.data, aes(sample=sample)) + stat_qq() + stat_qqline()
> ggplot(test.data.2, aes(sample=sample)) + stat_qq(distribution=qt, dparams=list(df=2)) +
+   stat_qqline(distribution=qt, dparams=list(df=2))

(不幸的是,由于qqline在一个单独的层上,我找不到“重用”分发参数的方法,但这应该只是一个小问题。)

答案 4 :(得分:9)

为什么不以下?

给出一些矢量,比如说,

myresiduals <- rnorm(100) ^ 2

ggplot(data=as.data.frame(qqnorm( myresiduals , plot=F)), mapping=aes(x=x, y=y)) + 
    geom_point() + geom_smooth(method="lm", se=FALSE)

但我们必须使用传统的图形功能来支持ggplot2,这似乎很奇怪。

我们不能以某种方式获得相同的效果,从我们想要分位数图的向量开始,然后在ggplot2中应用适当的“stat”和“geom”函数?

Hadley Wickham是否监控这些帖子?也许他可以向我们展示更好的方式。

答案 5 :(得分:6)

使用最新的ggplot2版本(&gt; = 3.0),实现了新的函数library(ggplot2) model <- lm(mpg ~ wt, data=mtcars) ggplot(model, aes(sample = rstandard(model))) + geom_qq() + stat_qq_line() https://github.com/tidyverse/ggplot2/blob/master/NEWS.md),并且可以添加模型残差的qq行:

rstandard(model)
获得标准化残差需要

install.packages("ggplot2")。 (信用@jlhoward和@qwr)

如果你在stat_qq_line()中遇到'错误:找不到函数“stat_qq_line”',你的ggplot2版本太旧了,你可以通过升级你的ggplot2包修复它:document.onload = async function(){ const slider = await import(/* webpackChunkName: "slider" */ 'slider'); }

答案 6 :(得分:4)

你可以从使用普通概率纸做过这些东西的老人那里偷一页。仔细查看ggplot()+ stat_qq()图形表明可以使用geom_abline()添加参考线,就像这样

 Syntax error near:"DATEADD(" Unexpected token "(" at line 0, column 11.

答案 7 :(得分:0)

ggplot2 v.3.0.0现在具有一个qqline统计信息。在帮助页面中:

df <- data.frame(y = rt(200, df = 5))
p <- ggplot(df, aes(sample = y))
p + stat_qq() + stat_qq_line()

!ggplot2 v3.0.0 Example stats equivalent to qqnorm plus abline] 1