Hierarchical reordering of factor levels

Is it possible to implement a hierarchical (~ group by) reordering with the fct_reorder()?
An use case can be the following type of plot:

fct_reorder_hierarchy
I have already a workaround for this, just I am wondering if I could implement it more elegantly with the help of fct_reorder() in one command.

Can you share the data? This will make it easier to help!

library(tidyverse)
Data_stacked = tribble(~Cond, ~Group, ~Amount,
                       "A",    "X",     1,
                       "B",    "X",     4,
                       "C",    "X",     2,
                       "D",    "X",     6,
                       "E",    "Y",     7,
                       "F",    "Y",     5,
                       "G",    "Y",     3,
                       "H",    "Y",     4  )

Another workaround, defining the order seperately by sorting the initial dataframe.

order = Data_stacked %>%
  arrange(Group, desc(Amount)) %>%
  pull(Cond)

# ordered  
ggplot(Data_stacked, aes(x=fct_reorder(Cond, order), y=Amount, fill=Group)) + theme_bw() +
  geom_col() 

image

If necessarry you can put this in one line, however I wouldn't recommend this.

ggplot(Data_stacked, aes(x=fct_reorder(Cond, 
                                       pull(arrange(Data_stacked, Group, desc(Amount)), Cond)), 
                         y=Amount, fill=Group)) + theme_bw() +
  geom_col()
1 Like

Thank you.
I would be a bit more elegant if the fct_reorder2() could include an option for hierarchical ordering.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.