且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

控制ggplot2 geom_bar的填充顺序和组

更新时间:2023-01-28 12:59:08

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

You need first to format your dataframe without factor. Then you need to define the x column as factor but with order depending on y minimum per group. This specific ordering you want needs to be specified in levels argument.

我们在这里:

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