r - Ordering grouped geom_bar left to right by height
问题描述
The following R script:
library(ggplot2)
data <- read.csv(text="x,value,version
foo,10,one
foo,12,two
bar,8,one
bar,7,two
baz,11,one
baz,14,two", header=TRUE)
png(filename="so.png")
ggplot(data,aes(data$x,data$value,fill=data$version)) +
geom_bar(stat="identity",position="dodge") +
scale_fill_brewer(palette="Set1") +
labs(x = "x",y="value") +
guides(fill=guide_legend(title="version"))
dev.off()
Produces the following graph:
They appear left to right according to the "x" column (foo, bar, baz) alphabetically. However, I'd like the "x" column-grouped bars to appear according one of the versions, left most being the highest "value" column value. E.g. left to right according to values of "one" version. Thus:
- left most: baz (one:11,two:14)
- middle: foo (one:10,two:12)
- right most: bar (one:8,two:7)
How can I achieve this?
解决方案
我引用的问题的一般原则始终成立:您通过设置因子水平顺序来控制顺序。许多人被绊倒了,因为该问题的答案并不总是准确地告诉您如何在每种情况下重新排列您的因素。但想法总是一样的。以下是按顺序设置因子水平的多种方法:
#Cleverly
library(forcats)
data$x <- fct_reorder2(.f = data$x,
x = data$value,
y = data$version,
fun = function(x,y) x[y == "one"])
#Manually
data$x <- factor(data$x,levels = c("baz","foo","bar"))
#Tortuously
levels(data$x) <- data$x[data$version == "one"][order(data$value[data$version == "one"],decreasing = TRUE)]
#tidily
library(dplyr)
levels(data$x) <- data %>%
filter(version == "one") %>%
arrange(desc(value)) %>%
pull(x)
推荐阅读
- android - Remove ripple effect from AutoCompleteTextView
- python - 如何在 Django 中正确构建和使用我的模型和表?
- artifactory - 如何将工件从一个工件实例复制到另一个?
- c# - 在 IGrouping 中创建 IGrouping
- dynamics-365 - 尝试使用 API 在 Microsoft Dynamics 365 Business Central 上更新客户时出错
- java - 无法在 netbeans 中建立 jdbc。错误登录失败
- azure - 如何通过 PowerShell 或 ARM 模板在 Azure 数据资源管理器中创建表和摄取映射
- javascript - Firebase 云功能 onUpdate 已触发,但未按要求执行
- node.js - Mongoose 查询过滤器
- typo3 - 如何在 TYPO3 前端显示 rte 内容时省略 html 标签?