简体   繁体   中英

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). What should I change?

With the interaction between Type and FLAG the bars display the counts per groups of both.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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