如何通过多个变量对条形图重新排序

how to reorder bars by multiple variables

我想制作条形图并根据 GradeScore 订购条形图。抱歉我的问题听起来很愚蠢。我知道如何按一个变量 le 排序,但不知道如何按两个变量排序。谁能教教我?

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)

我可以按等级排序,但不知道如何进一步按 Score 排序。

试试这个经典技巧:

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)

使用 tidyverse 中的 forcats 包创建一个按 as.numeric(Grade) + as.numeric(Score) 排序的变量,然后在 geom_bar 调用中按该单个变量 reorder 排序。

您可以在完成后从数据中删除 reord 变量,因为它只是一个临时辅助变量。

这是一个方法。用想要的顺序创建一个变量 ord 并在 reorder 调用中使用它。

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
  )

reprex package (v2.0.1)

创建于 2022-05-27

这将按年级和分数降序排列:

df %>% arrange(across(.cols=c("Grade", "Score"))) %>% 
  rowid_to_column() %>% 
ggplot()  +
  geom_bar(aes(y =  reorder(ID, rowid),  x = Score, fill = Grade), stat = "identity",  width = 0.8)

产生: