ggplot中的条形图 - 闪避位置+计数

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 标记 1 和 1 观察结果)。我应该改变什么?

interactionTypeFLAG 之间,条形图显示每组的计数。

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_col() 进行一些预处理来替换 stat_count()geom_bar()。这是一个例子:

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() 唯一做的就是将变量名从大写字母和空格分别转换为小写字母和下划线。