【问题标题】:Mapping a sum across categories to an aesthetic in ggplot2将跨类别的总和映射到ggplot2中的美学
【发布时间】:2015-04-30 18:49:29
【问题描述】:

我的数据包含几个样本、两个条件的组合以及这些条件的结果,在这种情况下是真阳性的数量和假阳性的数量。

我想出的最好的显示方式是堆积点图。这是单个样本的结果,看起来基本上是我想要的结果:

现在,我想做的是将所有样本的真假阳性总数相加,并以完全相同的方式绘制它们。当我尝试时,每个样本的所有点都会堆叠在一起,而不是相加并绘制在一起,如下所示:

(注意靶心图案,每个点应该只有 2 个圆圈。)

这是一些相同形式的较小样本数据,以及我尝试过的方法,使用 stat_sum():

require(dplyr)

samples <- c(rep("Sample 1", 4), rep("Sample 2", 4), rep("Sample 3", 4))
cond1 <- c("A", "A", "B", "B")
cond2 <- rep(c("X", "Y"))

data <- as.data.frame(cbind(samples, cond1, cond2))
data$true <- sample(30, length(data$samples))
data$false <- sample(20, length(data$samples))

data <- gather(data, type, hits, true, false)

#The good single-sample version
ggplot(filter(data, sample == "Sample 1"), aes(
    x = cond1, y = cond2, size = hits, color = type)) +
  geom_point(alpha = 0.2) +
  scale_size_area(max_size = 20)

#Trying stat_sum() across hits
ggplot(data, aes(x = cond1, y = cond2, size = hits, color = type)) +
  stat_sum(aes(group = hits), alpha =0.2) +
  scale_size_area(max_size = 20)

#Trying stat_sum() weighting by hits
ggplot(data, aes(x = cond1, y = cond2, size = hits, color = type)) +
  stat_sum(aes(group = 1, weight = hits), alpha =0.2) +
  scale_size_area(max_size = 20)

如何获得样本中真假命中的总和,并按条件绘制它们?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使用 dplyr 的 group_by() 和 summarise() 在绘图之前转换数据集的工作原理:

    require(dplyr)
    grouped_data <- group_by(data, cond1, cond2, type)
    summarize(grouped_data, hits = sum(hits))
    
    ggplot(grouped_data, aes(x = cond1, y = cond2, size = hits, color = type)) +
    geom_point(alpha = 0.2) +
    scale_size_area(max_size = 20)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多