如何使用 ggplot 在 R 中的多面堆叠条形图中使用不同的 geom_text() 标签?

How can I have different geom_text() labels in a faceted, stacked bar graph in R with ggplot?

我正在尝试将 facet_wrap 与堆叠条形图一起使用,我希望在条形图上添加标签以显示条形图每个部分的值。

以钻石数据集为例:

我的 geom_text 代码在只有一个图表时工作正常,尽管对于较短的条形图来说有些局促:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
geom_text(data = . %>% 
          group_by(cut, clarity) %>%
          tally() %>%
          ungroup() %>% 
          group_by(cut) %>%
          ungroup(),
        aes(y = n, label = n),
        position = position_stack(0.5),
        show.legend = FALSE) 

Labeled bar plot without faceting

但是,当我添加分面时,所有标签都显示在所有单独的分面中:

diamonds %>%
  ggplot(aes(x = cut, fill = clarity)) +
  geom_bar() +
  facet_wrap(~ color) +
  geom_text(data = . %>% 
              group_by(cut, clarity) %>%
              tally() %>%
              ungroup() %>% 
              group_by(cut) %>%
              ungroup(),
            aes(y = n, label = n),
            position = position_stack(0.5),
            show.legend = FALSE)

Faceted bar plot with replicated labeling

我怎样才能让标签只显示在相关栏上?

谢谢!

我认为您需要在 group_by + 计数中包含颜色,以便可以将其分配给正确的面:

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
geom_text(data = . %>% 
          count(cut, clarity,color),
            aes(y = n, label = n),size=1,
            position = position_stack(0.5),
            show.legend = FALSE)

就个人而言,我发现 ..count.. 特殊变量更易于使用。

diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
  geom_bar() +
  facet_wrap(~ color,scale="free_y") +
  stat_count(geom = "text", 
             aes(y =..count.., label = ..count..),
             position=position_stack(0.5), size = 2)