反转堆叠柱状图顺序 [英] Reverse stacked bar order

查看:50
本文介绍了反转堆叠柱状图顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这给了我这样的东西:

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

我已经看到了许多关于此的问题(例如

这是原图:

ggplot(plot_df, aes(group, fill = levels)) +geom_bar(位置=填充")

或者,按照

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

I'm creating a stacked bar chart using ggplot like this:

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

Which gives me something like this:

How do I reverse the order the stacked bars themselves, so that level 1 is at the bottom, and level 5 is at the top of each bar?

I've seen a number of questions on this (e.g. How to control ordering of stacked bar chart using identity on ggplot2) and the common solution seems to be to reorder the dataframe by that level as that what ggplot is using the determine the order

So I've tried reordering using dplyr:

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

However, the plot comes out the same. It also doesn't seem to make a difference whether I arrange by ascending or descending order

Here is a reproducible example:

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

This is the original plot:

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

Or, using position_fill(reverse = TRUE) as suggested by alistaire in his comment:

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

Note that the levels (colors) in the legend is not in the same order as in the stacked bars.

这篇关于反转堆叠柱状图顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆