繁体   English   中英

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

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

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

以 diamonds 数据集为例:

当只有一个图形时,我的 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) 

标记条 plot 不带刻面

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

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)

带复制标签的刻面条 plot

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

谢谢!

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

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)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM