使用 ggplot 的条形图重新排序无法正常工作

use*_*413 1 r ggplot2

这是数据集:https : //www.dropbox.com/s/mrlfnh6e2ww1xwd/home.csv?dl=0

这是我的代码:

hom <- read.csv(file.choose(),header=TRUE)
home.melt <- melt(hom, id.vars='home')

ggplot(home.melt, 
aes(x = reorder(home, value), y = value, 
fill=forcats::fct_rev(variable))) + 
geom_bar(stat = "identity",width = 0.8) + coord_flip() +
theme_minimal(base_size=10) +
labs(title="Home time",
   subtitle="By matches",
   x="Home",
   y="time (minutes)",
   fill=" ")
Run Code Online (Sandbox Code Playgroud)

这是输出:

在此处输入图片说明

如您所见,它不是按降序排列的。

mis*_*use 5

关键是在调用重新排序时指定函数:

reorder(home, value, FUN = sum)
Run Code Online (Sandbox Code Playgroud)

默认为“平均”

 ggplot(home.melt, 
               aes(x = reorder(home, value, FUN = sum), y = value, 
                   fill=forcats::fct_rev(variable))) + 
          geom_bar(stat = "identity",width = 0.8) + coord_flip() +
          theme_minimal(base_size=10) +
          labs(title="Home time",
               subtitle="By matches",
               x="Home",
               y="time (minutes)",
               fill=" ")
Run Code Online (Sandbox Code Playgroud)