geom_tile() 在 R 中:排序顺序

geom_tile() in R: Sort Order

我有一个数据框,我想绘制以下热图:

dput(df)
structure(list(`0` = c(6.08, 7.91, 5.14, 2.23, 0.72, 0.19, 0.04, 
0.01, 0, 0, 0), `1` = c(9.12, 11.86, 7.71, 3.34, 1.09, 0.28, 
0.06, 0.01, 0, 0, 0), `2` = c(6.84, 8.89, 5.78, 2.5, 0.81, 0.21, 
0.05, 0.01, 0, 0, 0), `3` = c(3.42, 4.45, 2.89, 1.25, 0.41, 0.11, 
0.02, 0, 0, 0, 0), `4` = c(1.28, 1.67, 1.08, 0.47, 0.15, 0.04, 
0.01, 0, 0, 0, 0), `5` = c(0.38, 0.5, 0.33, 0.14, 0.05, 0.01, 
0, 0, 0, 0, 0), `6` = c(0.1, 0.13, 0.08, 0.04, 0.01, 0, 0, 0, 
0, 0, 0), `7` = c(0.02, 0.03, 0.02, 0.01, 0, 0, 0, 0, 0, 0, 0
), `8` = c(0, 0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0), `9` = c(0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), `10 or more` = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0)), row.names = c("0", "1", "2", "3", "4", "5", 
"6", "7", "8", "9", "10 or more"), class = "data.frame")

现在使用 ggplot2 绘制热图,这就是我解决问题的方法:

df %>% 
as_tibble(rownames = "homeScore") %>%
pivot_longer(cols = -homeScore, names_to = "awayScore", values_to = "level") %>%
ggplot() +geom_tile(aes(x=homeScore, y=awayScore, fill = level))

我面临的问题是列和行是按 (0,1,10+,2,..) 而不是 (0,1,2,...10+) 排序的。这是示例:

如何对值进行排序,使 10+ 成为行和列的最后一个,而不是第三个?

正如@Nate 已经提到的,您必须将您的变量转换为因数,并将级别按正确的顺序排列。与其通过 factor(as.numeric(.)) 进行转换(将“10 或更多”转换为 NA),我建议使用 forcats::fct_relevel,它允许您更改级别的顺序,例如forcats::fct_relevel(homeScore, "10 or more", after = 10) 将更改级别的顺序,使 10 or more 成为最后一个级别。试试这个:

library(ggplot2)
library(tidyr)
library(dplyr)
library(forcats)

df %>% 
  as_tibble(rownames = "homeScore") %>%
  pivot_longer(cols = -homeScore, names_to = "awayScore", values_to = "level") %>%
  mutate_at(vars(homeScore, awayScore), ~forcats::fct_relevel(.x, "10 or more", after = 10)) %>% 
  ggplot() + 
  geom_tile(aes(x=homeScore, y=awayScore, fill = level))