ggplot2:在每个堆叠图中添加两个观察值

ggplot2: Add two number of observation in each stacked graph

我有一个 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。在这种情况下,每个条形都有两个 n 观察值,条形上方有一个作为每种颜色的总 n(正如您已经看到的),在 TRUE 条形上方是该特定颜色的 TRUE n 观察值...

可以做到,例如这样,首先通过 RipeColor 进行聚合以获得两个位置

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 + Ripe, data = fruit, FUN = length)
labs <- data.frame(Sample = c(foo[foo$Ripe == TRUE, "Sample"], aggregate(Sample ~ Color, data = foo2, FUN = sum)$Sample))

ggplot() +
  geom_bar(data = fruit, aes(Color, fill = Color, alpha = Ripe), color = "black") +
  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))) +
  geom_text(data = labs, aes(label = Sample, x = rep(1:3, 2), y = Sample), alpha = "1", vjust = -1, color = "black")

您可以添加更多聚合:

foo2 <- aggregate(Ripe ~ Color, data = fruit, FUN = sum)

foo2$label <- foo2$Ripe
foo$label <- foo$Sample
foo_stack <- do.call(rbind, list(foo[,c("Color", "label")], foo2[,c("Color","label")]))

然后将您的 geom_text() 更改为:

geom_text(data = foo_stack, aes(label = label, y = label), alpha = "1", vjust = -1)

或者,您可以一步完成 data.table 中的所有聚合,例如:

library(data.table)
foo_stack <- as.data.table(fruit)    
foo_stack[,.(labels = c(sum(Ripe == TRUE), length(Ripe))) , by = Color]