控制 ggplot2 geom_bar 的填充顺序和组

Control the fill order and groups for a ggplot2 geom_bar

library(ggplot2)


 data <- 
  data.frame(
    group=factor(c("a","c","b","b","c","a")),
    x=c("A","B","C", "D","E","F"),
    y=c(3,2,10,11,4,5)) 

> data
  group x  y
1     a A  3
2     c B  2
3     b C 10
4     b D 11
5     c E  4
6     a F  5

#And plot this:
ggplot(data)+
  geom_bar(aes(x=x, y=y, fill=group, order=group),
           stat="identity",
           position="dodge")+
  coord_flip()

这给出了一个图,其中 x 是根据因子水平绘制的:

但是如何根据 group 变量的自定义顺序对 x 重新排序,同时根据降序 ygroup 内排列。例如,如果我想先绘制 "c"(红色),然后绘制 "a"(绿色),然后绘制 "b"(蓝色)组,则 x 轴的绘制顺序 (x 变量)将是:E、B、F、A、D、C。请注意,这可能与 this SO 问题相似。

您首先需要在没有 factor 的情况下格式化您的数据框。然后您需要将 x 列定义为 factor,但顺序取决于每个 group 的最小值 y。您需要的特定顺序需要在 levels 参数中指定。

开始吧:

data <- 
  data.frame(
    group=c("a","c","b","b","c","a"),
    x=c("A","B","C", "D","E","F"),
    y=c(3,2,10,11,4,5)) 

data$x = with(data, factor(x, levels=x[order(ave(y, group, FUN=min),y)]))

ggplot(data, aes(x, y, fill=group)) + 
  geom_bar(stat='identity', position='dodge') + 
  coord_flip()