r - 按值对堆积条形图进行排序
问题描述
这与现有的问题不同。其他答案指向的是根据指定的顺序移动整个条形图。我想根据堆叠条中的一个元素对结果条进行排序。
我在 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))
解决方案
我认为你已经做得很好了,你把它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 日创建
推荐阅读
- ios - 按下表格视图单元格后重定向到注释
- python - Maya – 实时网格上的描边
- python - 如何将列添加到现有表?在 Flask SqlAlchemy 中
- apache - 通过网页使 perl 脚本可执行
- r - 循环几个excel文件以创建不同的数据框,在R中执行分组并保存为单个df
- reactjs - 在 windows 和 mac 之间对 VScode 进行 React 版本控制
- http - 当网页在我的浏览器中正常工作时,http.Get 在一次使用后返回错误 429 请求过多
- php - php get_file_contents foreach 目录中的文件
- c# - 计算 n+nn+nnn 的分层值
- android - 强制元素停留在约束边界内