ggplot2中的qqnorm和qqline [英] qqnorm and qqline in ggplot2

查看:934
本文介绍了ggplot2中的qqnorm和qqline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个线性模型LM,我想要一个qq的残差图。通常情况下,我会使用R底图:

  qqnorm(残差(LM),ylab =残差)
qqline(residuals(LM))

我可以计算出如何获得图的qqnorm部分,但我似乎无法管理qqline:

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

我怀疑我错过了一些非常基本的东西,但它似乎应该这是一个简单的方法。



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



<$ p $ (LM $ residual)(LM $渣油)]]> ggQQ < - 函数(LM)#参数:线性模型
{
y < ,c(0.25,0.75))
x <-qnorm(c(0.25,0.75))
斜率<-diff(y)/ diff(x)
int <-y [1L] - 斜率* x [1L]
p < - ggplot(LM,aes(sample = .resid))+
stat_qq(alpha = 0.5)+
geom_abline(slope = slope ,intercept = int,color =blue)

return(p)
}


解决方案

下面的代码会给你你想要的情节。 ggplot包似乎没有包含用于计算qqline参数的代码,所以我不知道是否有可能在(可理解的)单线程中实现这样的情节。

  qqplot.data<  - 函数(vec)#参数:数字向量
{
#从基本R的qqline()
y< - 分位数(vec [!is.na(vec)],c(0.25,0.75))
x <-qnorm(c(0.25,0.75))
斜率< - 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)

}


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(residuals(LM))

I can figure out how to get the qqnorm part of the plot, but I can't seem to manage the qqline:

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

I suspect I'm missing something pretty basic, but it seems like there ought to be an easy way of doing this.

EDIT: Many thanks for the solution below. I've modified the code (very slightly) to extract the information from the linear model so that the plot works like the convenience plot in the R base graphics package.

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

解决方案

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)

}

这篇关于ggplot2中的qqnorm和qqline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆