ggplot2:在堆积条上标记n对alpha的观察

时间:2018-01-30 18:34:50

标签: r ggplot2 bar-chart geom-text

我有一个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)))

通过上面的命令,我可以创建以下条形图:

enter image description here

所以......我能够将每种颜色的观察总数放在每个条形图上面......但是我不这样做....相反,我很想知道如何将总数n放在相反,在每个颜色条中观察到TRUE。在这种情况下,对于每个柱子,它将是一个n观察值,其中一个在上面的TRUE条上面,用于该特定颜色的TRUE n观察...

1 个答案:

答案 0 :(得分:1)

您可以在stat

中使用ggplot2的计算能力

enter image description here

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