ggplot2:在堆叠条上标记 n 个 alpha 观察值

ggplot2: label n observations for alpha on stacked bars

我有一个 df 如下:

fruit <- data.frame(Sample=1:100, 
        Fruit=c(rep("Apple", 10), rep("Strawberry", 25), rep("Grape", 20), 
              rep("Watermelon", 15), rep("Lime", 11), rep("Blueberry", 10), 
              rep("Plum", 9)), 
        Color=c(rep("Red", 30), rep("Green", 45), 
                rep("Blue", 25)), 
        Ripe=c(rep(c(T, F), 50)))+

fruit$Fruit <- factor(fruit$Fruit, unique(fruit$Fruit))+
fruit$Color <- factor(fruit$Color, unique(fruit$Color))

然后,我绘制了条形图:

foo <- aggregate(Sample ~ Color, data = fruit, FUN = length)

library(ggplot2)
ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
geom_bar(color = "black") +
geom_text(data = foo, aes(label = Sample, y = Sample), alpha = "1", vjust = -1)
scale_alpha_discrete(range = c(1, 0.6)) +
theme(axis.title.x = element_blank(), 
      axis.text.x = element_blank(), 
      axis.ticks.x = element_blank()) +
guides(fill = guide_legend(override.aes = list(colour = NA)))

使用上面的命令,我能够创建以下条形图:

所以...我能够将每种颜色的观察总数放在每个条形上方...但我没有这样做....相反,我想知道如何将总数取而代之的是在每个颜色条中对 TRUE 的观察。在这种情况下,每个条形图将是一个 n 观察值,在 TRUE 条形图上方有一个观察值,用于该特定颜色的 TRUE n 观察值...

您可以在ggplot2

中使用stat的算力

ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
    geom_bar() +
    geom_text(stat = "count", aes(y = ..count.., label = ..count..), 
              position = "stack", show.legend = FALSE) +
    scale_alpha_discrete(range = c(1, 0.6)) +
    theme(axis.title.x = element_blank(), 
          axis.text.x = element_blank(), 
          axis.ticks.x = element_blank()) +
    guides(fill = guide_legend(override.aes = list(colour = NA)))