簡體   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