I'd like to plot a QQ plot with x as one sample and y as another (not the common ones which x-axis=theoretical and y-axis=sample) using ggplot2. Does anyone know how to do this?
The common one would be, for example:
ggplot(df, aes(sample=sample)) + stat_qq()
I am able to do this with qqplot() function,
qqplot(sample1,sample2)
but it seems cannot display multiple plots with grid.arrange(). Or maybe anyone knows some other ways to plot multiple sub-qqplot at one plot?
It's not clear if this is what you mean, but you can add 2 stat_qq calls on the same plot:
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)

The other possibility is that you mean to have one sample on the x axis and one sample on the y axis to compare their relative ordering. You could do that like this:
ggplot(mapping = aes(x = sort(sample1), y = sort(sample2))) +
geom_point() +
geom_abline(aes(slope = 1, intercept = 0), linetype = 2)

Edit
From the comments, it is clear the OP is looking for an empirical qq plot of two vectors. This function should provide a rough ggplot equivalent of the function referenced in the comments:
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))
}
So, for example we can do:
qq <- gg_qq_empirical(sample1, sample2)
qq + theme_light() + coord_equal()
Created on 2020-07-03 by the reprex package (v0.3.0)
d <- tibble(Group=rep(1:2, each=200), Sample=c(rnorm(200), rnorm(200, mean=2, sd=4)))
d %>% ggplot(aes(sample=Sample)) + stat_qq() + facet_wrap(~Group)
qplot(sample=Sample, data=d, color=as.factor(Group))
The stat_qq() call gives

The qplot() call gives

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With