2

I was trying to order the bars in descending order (all the segments together) using reorder(). However, this seems not to work. How can I do this?

library(tidyverse)

# Sample data frame
df <- data.frame(var = sample(paste0("x", 1:10), size = 100, replace = TRUE),
                 var2 = sample(c("A", "B", "C", "D"), size = 100, replace = TRUE))

# Stacked barplot
df %>% group_by(var) %>%
  count(var2) %>%
  ggplot(aes(x = reorder(var, n, fun = "sum"), y = n, fill = var2)) +  
    geom_col()
zx8754
  • 52,746
  • 12
  • 114
  • 209
D. Studer
  • 1,711
  • 1
  • 16
  • 35

2 Answers2

3

Another option is to use add_count together with fct_infreq():

library(tidyverse)

df %>% 
  add_count(var) %>% 
  ggplot(aes(x = fct_infreq(var), y = n, fill = var2)) +  
  geom_col()

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
2

It works if you use forcats::fct_reorder (part of the tidyverse) rather than reorder...

df %>% group_by(var) %>%
  count(var2) %>%
  ggplot(aes(x = fct_reorder(var, n, .fun = sum), y = n, fill = var2)) +  
  geom_col()
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32