简体   繁体   English

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

[英]Barplot in ggplot - dodge position + counting

Hey I have the following code:嘿,我有以下代码:

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()

but it doesnt work as I want.但它不能按我的意愿工作。 The graph is OK but instead displaying the total number of observations of each type I want to display the number of each flag (so instead 2 for "B" type I want to display 1 and 1 because for "B" we have 1 observation with FLAG 1 and 1 observations with FLAG 0).该图没问题,但我想显示每个标志的数量,而不是显示每种类型的观察总数(因此,对于“B”类型,我想显示 1 和 1,而不是 2,因为对于“B”,我们有 1 个观察带有 FLAG 0 的 FLAG 1 和 1 观测值)。 What should I change?我应该改变什么?

With the interaction between Type and FLAG the bars display the counts per groups of both.通过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()

在此处输入图像描述

You could replace the stat_count() and geom_bar() with a little pre-processing with count() and geom_col() .您可以使用 count() 和geom_bar()进行一些预处理来替换stat_count() count() geom_col() Here is an example:这是一个例子:

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()

The only thing janitor::clean_names() does is transform variable names, from uppercase and spaces to lowercase and underscores, respectively. janitor::clean_names()唯一要做的就是将变量名从大写和空格分别转换为小写和下划线。

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

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