Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reorder grouped bar chart by ascending order of *one* group

I have a df:

df1 <- data.frame(ID = c('a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1', 
                         'a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1'),
                  val = c(22, 15, 14, 17, 13, 16, 15, 12, 11, 12, 12, 16,
                          16, 16, 14, 17, 16.5, 13, 12, 12),
                  time = c("time1", "time1", "time1", "time1", "time1", "time1",
                           "time1", "time1", "time1", "time1","time2", "time2",
                           "time2", "time2", "time2", "time2", "time2", "time2", 
                           "time2", "time2"))

And I want to reorder the bars in ascending order of val but when time==time1, whereas at present I think the below orders the bars based on cumulative val at time1+time2:

ggplot(df1, aes(x=reorder(ID, val), y=val, fill=time)) +
  geom_bar(stat="identity", width=0.5, position=position_dodge()) 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Sometimes it’s convenient to sort the data.frame itself, then use fct_inorder to use that order directly:

library(forcats)
library(dplyr)

arrange(df1, time, val) |> 
  ggplot(aes(fct_inorder(ID), y=val, fill=time)) +
  geom_col(width=0.5, position=position_dodge()) 

Alternatively, use fct_reorder2:

ggplot(df1, aes(fct_reorder2(ID, desc(time), desc(val)), y=val, fill=time)) +
  geom_col(width=0.5, position=position_dodge())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading