Home > Software design >  ggplot2: Order stacked barplot by total number
ggplot2: Order stacked barplot by total number

Time:12-13

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

CodePudding user response:

Anoter 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

CodePudding user response:

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