且构网

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

重新排序闪避条形图(ggplot2)

更新时间:2022-01-10 06:43:02

您本质上是想用一件事来填充,而用另一件事来排序.因此,一种解决方案是将它们撬开并创建单独的"order"变量.值得注意的是,我不知道是否按值对条形进行排序,而不是使每个组"具有相同的顺序,这会使您的绘图更易于理解.....

You essentially want to fill by one thing, and order by another. A solution is thus to pry them apart and create a separate 'order' variable. Of note, I don't know if sorting your bars by value instead of having the same sequence each 'group' makes your plot more understandable.....

创建一些数据:

library(data.table)


set.seed(123)
dat <- expand.grid(group=LETTERS[1:3],
                   subgroup=LETTERS[1:3])
dat$value <- runif(nrow(dat))
setDT(dat)

创建订单变量:

dat[,order:=order(value),by=group]

创建情节

p1 <- ggplot(dat, aes(x=group,y=value, fill=subgroup,group=order))+
  geom_bar(aes(group=order),position="dodge", stat="identity") +
  coord_flip()
p1