【问题标题】:Faceted qqplots with ggplot2带有 ggplot2 的多面 qqplots
【发布时间】:2012-09-11 12:08:31
【问题描述】:

假设我有以下数据:

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

使用ggplot2,我如何使用facet 功能在一个命令中创建两个QQ图,即一个带有两个t样本,另一个带有两个高斯样本?

【问题讨论】:

    标签: r statistics ggplot2


    【解决方案1】:

    首先,合并两个数据框:

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

    然后,对数据进行排序:

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

    如果两个样本向量的长度相同,这很简单:

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

    n = 1000 的示例:

    【讨论】:

    • 我认为使用scales = "free"的图表会更有用
    • 有趣的解决方案。到目前为止,我一直在尝试使用stat_qq,但无济于事。
    • 我认为解决方案有问题,情节似乎以某种方式被“砍掉”。使用两个法线更容易看到问题:datapoints1 = data.frame(categ=c(rep(1, n), rep(2, n)), vals1=c(rnorm(n, 2, 1), rnorm(n, 5, 1)), vals2=c(rnorm(n, 2, 1), rnorm(n, 5, 1)))。还要观察当您删除 scales = "free" 选项时会发生什么。
    • 不,不知何故,数据本身似乎被截断了(当您删除 scales = "free" 选项时,这会变得很明显)。这些 qqplots 应该看起来是对称的——在之前的评论中,我绘制了一个 N(2,1) 样本与另一个样本,以及一个 N(5,1) 样本与另一个样本,它们看起来也不是对称的。只需将您获得的结果与经典的 qqplot(rnorm(n, 2, 1), rnorm(n, 2, 1) 进行比较,您就会明白我的意思。
    • 对于您提到的情况,它们看起来相同,但在 faceted 情节中似乎出了点问题。您是否检查了我在上面的评论中建议的示例?试试n=1000; dat = data.frame(categ=c(rep(1, n), rep(2, n)), vals1=c(rnorm(n, 2, 1), rnorm(n, 5, 1)), vals2=c(rnorm(n, 2, 1), rnorm(n, 5, 1))); ggplot() + geom_point(data = dat, aes(x = sort(vals1), y = sort(vals2))) + facet_wrap( ~ categ)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多