按值对堆积的条形图进行排序

时间:2019-01-17 20:32:48

标签: r ggplot2 dplyr

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

我已经在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的标题。 然后用这个绘制它:

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()Final_3rd的小标题进行排序,但我认为gather()可能以后会变得混乱。

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

2 个答案:

答案 0 :(得分:0)

我想你想要这个: this

将数据用作data

library(data.table)
library(tidyr)

data2 <- as.data.table(gather(data, variable, value, Own_3rd:Final_3rd))

team_levels <- unique(data2[, Team])[order(data2[variable == "Final_3rd", value])]

data2$Team2 <- factor(data2$Team, levels = team_levels)

ggplot(data = data2,
       aes(x = Team2, y = value, fill = variable)) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()

答案基于:Change the order of a discrete x scale

答案 1 :(得分:0)

我认为您已经做了出色的工作,并使用`%in2%` <- function(lhs, rhs) purrr::has_element(rhs, lhs) c(5,6) %in2% list1 #[1] TRUE 6 %in2% list1 #[1] TRUE 2 %in2% list1 #[1] FALSE list(2, c(5,6)) %in2% list1 #[1] TRUE 正确地将其放置在arrange之后。那么一个窍门可能是为gather获取一个新的因子,其级别根据Team的值排序,而不是默认的字母顺序。

"Final_3rd"

reprex package(v0.2.1)于2019-01-17创建