【问题标题】:Matrix of density plots with each plot overlaying two distributions密度图矩阵,每个图覆盖两个分布
【发布时间】:2013-01-25 17:36:00
【问题描述】:

我有一个有 5 列的data.frame,我想生成一个密度图矩阵,这样每个密度图都是两个密度图的叠加。 (这类似于 plotmatrix,除了在我的情况下,每列中非 NA 值的数量因列而异,我想要叠加分布而不是散点图)。

下面是我的第一次尝试,但没有成功:

library(ggplot2)
library(reshape)

tmp1 <- data.frame(do.call(cbind, lapply(1:5, function(x) {
  r <- rnorm(100)
  r[sample(1:100, 20)] <- NA
  return(r)
})))

ggplot( melt(tmp1), aes(x=value, fill=variable))+
  geom_density(alpha=0.2, position="identity")+opts(legend.position = "none")+
  facet_grid(variable ~ variable)

我的第二种方法让我几乎做到了,但我不想使用 5 种不同的颜色,而只想在所有绘图中使用两种颜色。而且,我确信有一种更优雅的方式来构建这个扩展矩阵:

tmp2 <- do.call(rbind, lapply(1:5, function(i) {
  do.call(rbind, lapply(1:5, function(j) {
    r <- rbind(data.frame(var=sprintf('X%d', i), val=tmp1[,i]),
               data.frame(var=sprintf('X%d', j), val=tmp1[,j]))
    r <- data.frame(xx=sprintf('X%d', i), yy=sprintf('X%d', j), r)
    return(r)
  }))
}))
ggplot(tmp2, aes(x=val, fill=var))+
  geom_density(alpha=0.2, position="identity")+opts(legend.position = "none")+
  facet_grid(xx ~ yy)

我的解决方案是手动循环遍历成对的列并手动生成重叠的密度图,并将它们保存到列表中。然后我使用“grid.arrange”将它们排列在一个网格中,如下图所示。

但是是否可以使用facet_grid 来实现呢?

【问题讨论】:

    标签: r matrix ggplot2 dataframe


    【解决方案1】:

    最简单的方法是使用所有排列(5 * 5 = 25 个)重塑您的数据。

    require(gregmisc)
    perm <- permutations(5, 2, paste0("X", 1:5), repeats.allowed=TRUE)
    # instead of gregmisc + permutations, you can use expand.grid from base as:
    # perm <- expand.grid(paste0("X", 1:5), paste0("X", 1:5))
    o <- apply(perm, 1, function(idx) {
        t <- tmp1[idx]
        names(t) <- c("A", "B")
        t$id1 <- idx[1]
        t$id2 <- idx[2]
        t
    })
    require(ggplot2)
    require(reshape2)    
    o <- do.call(rbind, o)
    o.m <- melt(o, c("id1", "id2"))
    o.m$id1 <- factor(o.m$id1)
    o.m$id2 <- factor(o.m$id2)
    p <- ggplot(o.m, aes(x = value))
    p <- p + geom_density(alpha = 0.2, position = "identity", aes(fill = variable)) 
    p <- p + theme(legend.position = "none")
    p <- p + facet_grid(id1 ~ id2)
    p
    

    【讨论】:

    • @Arun,这非常好。为什么使用 gregmisc 包排列函数可能比基本 R 更可取?一个简短的提示就足够了。谢谢。
    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多