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

how to reorder the bar by muti vars

I would like to make a bar plot and order the bar base on Grade and Score. Sorry for my question that might sounds silly. I know how to order by one variable le, but not two. Could any one teach me?

df<-structure(list(ID = c("A1-18-603", "A1-19-604", "A2-20-605", 
"A1-21-606", "A1-22-607", "A2-16-601", "A5-17-602", "A1-14-502", 
"A1-15-503", "A1-13-501", "A5-12-403", "A2-10-401", "A1-11-402", 
"A2-07-301", "A5-08-302", "A3-09-303", "A1-06-203", "A1-05-202", 
"A3-04-201", "A1-02-102", "A6-03-103", "A1-01-101"), Score = c(33.58, 
12.88, 12.65, 12.19, 11.5, 9.66, 3.45, 26.22, 13.11, 11.96, 78.42, 
38.64, 16.1, 54.74, 12.88, 9.2, 114.53, 25.76, 22.54, 15.87, 
13.11, 6.67), Grade = c("6", "6", "6", "6", "6", "6", "6", "5", 
"5", "5", "4", "4", "4", "3", "3", "3", "2", "2", "2", "1", "1", 
"1")), row.names = c(NA, -22L), class = "data.frame")

ggplot(data = df)  +
    geom_bar(aes(y =  reorder(ID, desc(Grade)),  x = Score, fill = Grade), stat = "identity",  width = 0.8)

I can order it by Grade, but don’t know how to further order it by Score.

enter image description here

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 :

Try this classic trick:

library(tidyverse)
df %>%
  mutate(reord = as.numeric(Grade) + as.numeric(Score),
         ID = fct_reorder(ID, reord, .desc = F)) %>% 
  ggplot() +
  geom_bar(aes(y =  reorder(ID, desc(Grade)),  x = Score, fill = Grade), stat = "identity",  width = 0.8)

Make a variable that orders by as.numeric(Grade) + as.numeric(Score) with the forcats package from tidyverse then reorder by that single variable instead in the geom_bar call.

You can just drop the reord variable from the data when you are done since it is just a temporary helper variable.

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