【问题标题】:Reverse stacked bar order反向堆叠条形顺序
【发布时间】:2017-07-31 07:21:33
【问题描述】:

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

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

这给了我这样的东西:

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

我已经看到了很多关于此的问题(例如How to control ordering of stacked bar chart using identity on ggplot2),常见的解决方案似乎是按该级别重新排序数据框,因为 ggplot 正在使用确定顺序

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

plot_df &lt;- df[!is.na(df$levels), ] %&gt;% 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")

【问题讨论】:

  • 观察的顺序没有意义,但因子水平的顺序有意义。还有,代表。
  • 是的,我也试过用levels(plot_df$levels) &lt;- c("1", "2", "3", "4", "5")(和相反的顺序)改变因子水平顺序,但它不会改变图形顺序
  • 还添加了数据示例
  • plot_df %&gt;% mutate(levels = factor(levels, levels = 5:1)) %&gt;% ggplot(aes(group, fill = levels)) + geom_bar(position = "fill") 或只是ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = position_fill(reverse = TRUE))

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


【解决方案1】:

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

这是原图

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

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

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

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

【讨论】:

  • position_fill(reverse = TRUE) 标准化条形图,如果您不想标准化条形图,请使用 position_stack(reverse = TRUE)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多