ggplot2做qqplot图

转载自http://stats.stackexchange.com/questions/12392/how-to-compare-two-datasets-with-q-q-plot-using-ggplot2

感谢csgillespie的答案

 

qqplot是可以直观反应两组数字是否属于同一分布的作图。ggplot2提供了一个qqplot的函数,但这个函数并不能对两组观测的数字进行作图。与此相对的是,R中却有原生函数qqplot来提供这个作图。

以下是如何利用qqplot函数的方法,使用ggplot来作图。

这是R中qqplot的原始方法:

R> qqplot
function (x, y, plot.it = TRUE, xlab = deparse(substitute(x)), 
    ylab = deparse(substitute(y)), ...) 
{
    sx <- sort(x)
    sy <- sort(y)
    lenx <- length(sx)
    leny <- length(sy)
    if (leny < lenx) 
        sx <- approx(1L:lenx, sx, n = leny)$y
    if (leny > lenx) 
        sy <- approx(1L:leny, sy, n = lenx)$y
    if (plot.it) 
        plot(sx, sy, xlab = xlab, ylab = ylab, ...)
    invisible(list(x = sx, y = sy))
}
<environment: namespace:stats>

这是ggplot利用同样方法进行作图的代码:

x <- rnorm(10);y <- rnorm(20)

sx <- sort(x); sy <- sort(y)
lenx <- length(sx)
leny <- length(sy)
if (leny < lenx)sx <- approx(1L:lenx, sx, n = leny)$y
if (leny > lenx)sy <- approx(1L:leny, sy, n = lenx)$y

require(ggplot2)
g = ggplot() + geom_point(aes(x=sx, y=sy))
g

 

posted on 2015-05-12 21:46  云中道长  阅读(4054)  评论(0编辑  收藏  举报

导航