Faceted qqplots with ggplot2

久未见 提交于 2021-02-08 03:44:53

问题


Say I have the following data:

datapoints1 = data.frame(categ=c(rep(1, n), rep(2, n)), vals1=c(rt(n, 1, 2), rnorm(n, 3, 4)))
datapoints2 = data.frame(categ=c(rep(1, n), rep(2, n)), vals2=c(rt(n, 5, 6), rnorm(n, 7, 8)))

Using ggplot2, how can I use the facet functionality to create in a single command two QQplots, i.e. one with the two t samples, the other with the two Gaussian samples?


回答1:


First, combine both data frames:

dat <- cbind(datapoints1, vals2 = datapoints2[ , 2])

Then, sort the data:

dat_sort <- do.call("rbind", lapply(unique(dat$categ), FUN = function(x) {data.frame(categ = x, vals1 = sort(dat$vals1[dat$categ == x]), vals2 = sort(dat$vals2[dat$categ == x]))}))

It is simple if both sample vectors are of the same length:

ggplot() + 
 geom_point(data = dat_sort, aes(x = vals1, y = vals2)) +
 facet_wrap( ~ categ, scales = "free")

An example with n = 1000:

2 QQ plots



来源:https://stackoverflow.com/questions/12369377/faceted-qqplots-with-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!