反向堆叠条形顺序

Reverse stacked bar order

我正在使用 ggplot 创建堆积条形图,如下所示:

plot_df <- df[!is.na(df$levels), ] 
ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill")

这给了我这样的东西:

如何颠倒堆叠条形本身的顺序,使第 1 层位于底部,而第 5 层位于每个条形的顶部?

我已经看到很多关于此的问题(例如 ),常见的解决方案似乎是按该级别重新排序数据框,因为 ggplot 使用的是确定顺序

所以我尝试使用 dplyr 重新排序:

plot_df <- df[!is.na(df$levels), ] %>% arrange(desc(levels))

然而,剧情是一样的。我按升序或降序排列似乎也没有什么区别

这是一个可重现的例子:

group <- c(1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4)
levels <- c("1","1","1","1","2","2","2","2","3","3","3","3","4","4","4","4","5","5","5","5","1","1","1","1")
plot_df <- data.frame(group, levels)

ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill")

The release notes of ggplot2 version 2.2.0 on Stacking bars suggest:

If you want to stack in the opposite order, try forcats::fct_rev()

library(ggplot2)   # version 2.2.1 used    
plot_df <- data.frame(group = rep(1:4, 6),
                      levels = factor(c(rep(1:5, each = 4), rep(1, 4))))
ggplot(plot_df, aes(group, fill = forcats::fct_rev(levels))) + 
  geom_bar(position = "fill")

这是原剧情:

ggplot(plot_df, aes(group, fill = levels)) + 
  geom_bar(position = "fill")

或者,按照 的建议使用 position_fill(reverse = TRUE)

ggplot(plot_df, aes(group, fill = levels)) + 
  geom_bar(position = position_fill(reverse = TRUE))

请注意,图例中的级别(颜色)与堆叠条中的顺序不同。

另一种方法是将因子重新排序,假设该因子称为“水平”: 级别 = 有序(级别,级别 = c(5,4,3,2,1))。 欲了解更多信息:http://www.cookbook-r.com/Manipulating_data/Changing_the_order_of_levels_of_a_factor/