首页 > 解决方案 > 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:

enter image description here

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:

How can I achieve this?

标签: rggplot2geom-bar

解决方案


我引用的问题的一般原则始终成立:您通过设置因子水平顺序来控制顺序。许多人被绊倒了,因为该问题的答案并不总是准确地告诉您如何在每种情况下重新排列您的因素。但想法总是一样的。以下是按顺序设置因子水平的多种方法:

#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)

推荐阅读