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

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

这是输出:

enter image description here

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

最佳答案

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

reorder(home, value, FUN = sum)

默认是“均值”

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

关于r - 使用 ggplot 的条形图重新排序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46103521/

相关文章:

r - 在 x 轴刻度上添加 latex 表达式 @ggplot2

r - 在R中跨 session 自动保存历史记录

r - 如何确定 R 中特定行周围的相似值?

R ggplot2 为因子分配颜色

R ggplot,删除 ggsave/ggplot 中的白边

r - 两列facet_grid,顶部带有条形标签

r - 从任何统计测试中获取单个值(例如,从cor.test中获取spearman rho的值)

Rmarkdown : spacing between parragraph and image

r - 在ggplot中添加正交回归线

r - 如何使用ggplotly创建多色分段线?