如何在ggplot2中绘制带有2个样本的QQ图?

Hel*_*ena 6 r ggplot2

我想使用 ggplot2 绘制一个 QQ 图,其中 x 作为一个样本,y 作为另一个样本(不是常见的 x 轴 = 理论和 y 轴 = 样本)。有谁知道如何做到这一点?

常见的例子是:

ggplot(df, aes(sample=sample)) + stat_qq() 
Run Code Online (Sandbox Code Playgroud)

我可以使用 qqplot() 函数来做到这一点,

qqplot(sample1,sample2)
Run Code Online (Sandbox Code Playgroud)

但似乎无法使用 grid.arrange() 显示多个图。或者也许有人知道在一个图上绘制多个子 qqplot 的其他方法?

All*_*ron 8

不清楚这是否是您的意思,但您可以stat_qq在同一个绘图上添加 2 个调用:

library(ggplot2)

set.seed(69)

sample1 <- rnorm(100)
sample2 <- rnorm(100)

ggplot() + 
  stat_qq(aes(sample = sample1), colour = "green") + 
  stat_qq(aes(sample = sample2), colour = "red") +
  geom_abline(aes(slope = 1, intercept = 0), linetype = 2)
Run Code Online (Sandbox Code Playgroud)

另一种可能性是您的意思是在 x 轴上有一个样本,在 y 轴上有一个样本来比较它们的相对顺序。你可以这样做:

ggplot(mapping = aes(x = sort(sample1), y = sort(sample2))) + 
  geom_point() +
  geom_abline(aes(slope = 1, intercept = 0), linetype = 2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


编辑

从评论中可以看出,OP 正在寻找两个向量的经验 qq 图。该函数应提供与注释中引用的函数大致等效的 ggplot:

gg_qq_empirical <- function(a, b, quantiles = seq(0, 1, 0.01))
{
  a_lab <- deparse(substitute(a))
  if(missing(b)) {
    b <- rnorm(length(a), mean(a), sd(a))
    b_lab <- "normal distribution"
  }
  else b_lab <- deparse(substitute(b))
  
  ggplot(mapping = aes(x = quantile(a, quantiles), 
                       y = quantile(b, quantiles))) + 
    geom_point() +
    geom_abline(aes(slope = 1, intercept = 0), linetype = 2) +
    labs(x = paste(deparse(substitute(a)), "quantiles"), 
         y = paste(deparse(substitute(b)), "quantiles"),
         title = paste("Empirical qq plot of", a_lab, "against", b_lab))
}
Run Code Online (Sandbox Code Playgroud)

因此,例如我们可以这样做:

qq <- gg_qq_empirical(sample1, sample2)
qq + theme_light() + coord_equal()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 由reprex 包(v0.3.0)于 2020-07-03 创建