反向堆叠条形顺序

时间:2017-03-10 04:08:23

标签: r ggplot2 dplyr bar-chart stacked-chart

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

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

这给了我这样的东西:

enter image description here

如何反转堆积条本身的顺序,以便第1级位于底部,第5级位于每个条形的顶部?

我已经看到了很多关于此的问题(例如How to control ordering of stacked bar chart using identity on ggplot2),而且常见的解决方案似乎是按照该级别重新排序数据框,因为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")

2 个答案:

答案 0 :(得分:42)

The release notes of ggplot2 version 2.2.0 on Stacking bars suggest

  

如果您想以相反的顺序堆叠,请尝试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")

Reverse levels

这是原始情节

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

Original plot

或者,使用alistaire in his comment建议的position_fill(reverse = TRUE)

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

enter image description here

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

答案 1 :(得分:-1)

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