Home > Software design >  how to reorder bars by multiple variables
how to reorder bars by multiple variables

Time:05-28

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

CodePudding user response:

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

CodePudding user response:

Here is a way. Create a variable ord with the wanted order and use it in the reorder call.

suppressPackageStartupMessages({
  library(dplyr)
  library(ggplot2)
})

df %>%
  mutate(ord = order(desc(Grade), Score)) %>%
  ggplot()   
  geom_bar(
    aes(
      y = reorder(ID, ord),  
      x = Score, fill = Grade
    ), 
    stat = "identity",  
    width = 0.8
  )

Created on 2022-05-27 by the enter image description here

  • Related