簡體   English   中英

ggplot 中的條形圖 - 閃避 position + 計數

[英]Barplot in ggplot - dodge position + counting

嘿,我有以下代碼:

df = data.frame(Type = c("A", "B", "A", "A", "B"), FLAG = c(1, 1, 0, 1, 0))
df

ggplot(df, aes(x = Type)) + geom_bar(stat = "count", aes(fill = factor(FLAG)), position = "dodge") + coord_flip() + stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5)) + theme_bw()

但它不能按我的意願工作。 該圖沒問題,但我想顯示每個標志的數量,而不是顯示每種類型的觀察總數(因此,對於“B”類型,我想顯示 1 和 1,而不是 2,因為對於“B”,我們有 1 個觀察帶有 FLAG 0 的 FLAG 1 和 1 觀測值)。 我應該改變什么?

通過TypeFLAG之間的interaction ,條形圖顯示兩者的每組計數。

ggplot(df, aes(x = interaction(Type, FLAG))) + 
  geom_bar(stat = "count", 
           aes(fill = factor(FLAG)), position = "dodge") + 
  coord_flip() + 
  stat_count(geom = "text", 
             aes(label = ..count..),
             position=position_stack(vjust=0.5),
             colour = "white", size = 3.5) + 
  theme_bw()

在此處輸入圖像描述

您可以使用 count() 和geom_bar()進行一些預處理來替換stat_count() count() geom_col() 這是一個例子:

df %>% 
  janitor::clean_names() %>% 
  count(type, flag) %>% 
  ggplot(aes(type, n, fill = as.factor(flag))) +
  geom_col(position = "dodge") +
  geom_text(aes(label = n, y = n - 0.05), color = "white", 
            position = position_dodge(width = 1)) +
  scale_y_continuous(breaks = 0:3, limits = c(0,3)) +
  labs(fill = "flag") +
  coord_flip() +
  theme_bw()

janitor::clean_names()唯一要做的就是將變量名從大寫和空格分別轉換為小寫和下划線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM