首页 > 解决方案 > 按值对堆积条形图进行排序

问题描述

这与现有的问题不同。其他答案指向的是根据指定的顺序移动整个条形图。我想根据堆叠条中的一个元素对结果条进行排序。

我在 R 中创建了一个堆积条形图。这是数据集:

dput(Pitch_third)
structure(list(Team = c("Millwall", "Birmingham", "Sheffield United",
                        "Rotherham", "Middlesbrough", "Wigan", "Aston Villa", "Blackburn",
                        "Bolton", "Brentford", "Bristol City", "Leeds", "Preston", "Queens Park Rangers",
                        "Stoke", "Derby", "Ipswich", "Norwich", "West Bromwich Albion",
                        "Nottingham Forest", "Swansea", "Hull", "Reading", "Sheffield Wednesday"), 
               Own_3rd = c(0.25, 0.25, 0.25, 0.29, 0.27, 0.28, 0.28, 0.3, 
                           0.29, 0.28, 0.28, 0.3, 0.28, 0.3, 0.27, 0.28, 0.3, 0.29, 0.29, 
                           0.3, 0.31, 0.3, 0.3, 0.31), 
               Middle_3rd = c(0.41, 0.42, 0.43, 
                              0.4, 0.43, 0.42, 0.44, 0.41, 0.42, 0.42, 0.43, 0.42, 0.42, 0.42, 
                              0.45, 0.45, 0.43, 0.44, 0.44, 0.43, 0.44, 0.45, 0.45, 0.45), 
               Final_3rd = c(0.35, 0.33, 0.32, 0.31, 0.3, 0.3, 0.29, 0.29, 
                             0.29, 0.29, 0.29, 0.29, 0.29, 0.29, 0.28, 0.27, 0.27, 0.27, 
                             0.27, 0.26, 0.26, 0.25, 0.25, 0.25)), 
          row.names = c(NA, -24L), 
          class = "data.frame")

然后我创建了一个Pitch_third从这些数据中调用的 tibble。然后用这个绘制它:

Pitch_third %>%
gather(variable, value, Own_3rd:Final_3rd) %>% 
ggplot(aes(x = Team, y = value, fill = variable)) + 
geom_bar(position = "fill", stat = "identity") +
coord_flip()

这是结果图:

如何对绘图进行排序,以便团队按变量 Final_3rd 而不是按字母顺序排序?

我曾尝试使用arrange()对 tibble 进行排序,Final_3rd但我认为gather()之后可能会搞砸。

Pitch_third <- arrange(Pitch_third, desc(Final_3rd))

标签: rggplot2dplyr

解决方案


我认为你已经做得很好了,你把它arrange放在了后面gather。然后一个技巧可能是Team根据"Final_3rd"'s 的值而不是默认的字母顺序来获得一个新的因素。

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tidyr)

Pitch_third %>%
  gather(variable, value, Own_3rd:Final_3rd) %>% 
  arrange(variable, value) %>% 
  # Create a new factor, with its levels sorted according to Final_3rd
  mutate(team_f = factor(Team, levels = .[.$variable == "Final_3rd", "Team"])) %>% 
  # or
  # mutate(team_f = factor(Team, levels = filter(., variable == "Final_3rd") %>% .$Team)) %>%
  ggplot(aes(x = team_f, y = value, fill = variable)) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()

reprex 包(v0.2.1)于 2019 年 1 月 17 日创建


推荐阅读