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

3
这里是数据集: 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=" ")

这里是输出结果:

enter image description here

如你所见,它没有按降序排列。

1
重新排序轴还是填充? - pogibas
云存储链接不被鼓励,因为它们往往会随着时间的推移而失效。 - Hack-R
根据总时间重新排序条形图。'St' 应该在顶部,然后是 'Ln',依此类推。 - user709413
2个回答

7
关键是在调用reorder时指定函数:
reorder(home, value, FUN = sum)

默认值为"mean"

 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=" ")

完成了,先生!运行正常。 - user709413

1
library(data.table)
library(ggplot2)

hom <- fread("home.csv")
home.melt <- melt(hom, "home")
home.melt[, variable := factor(variable, levels = sort(unique(variable), decreasing = TRUE))]

ggplot(home.melt, aes(home, value, fill = variable)) + 
    geom_bar(stat = "identity",width = 0.8) + 
    coord_flip() +
    theme_minimal(base_size = 10) +
    scale_x_discrete(limits = home.melt[, sum(value), home][order(V1), home]) +
    scale_fill_brewer(palette = "Dark2") +
    labs(title = "Home time",
         subtitle = "By matches",
         x = "Home",
         y = "Time (minutes)",
         fill = NULL)

enter image description here


谢谢你的帮助,但这不是按降序排列。应该将 'St' 放在最前面,然后是 'Ln' 等等。 - user709413
差不多!只是如果你看到我的原始图表,你会注意到a1、a2、a3......b7按照一定的顺序堆叠,也就是说,a1最靠近y轴,b7最远离y轴。我希望保持这种顺序,除了你的代码实现之外。 - user709413

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接