【发布时间】: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 <- 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")
【问题讨论】:
-
观察的顺序没有意义,但因子水平的顺序有意义。还有,代表。
-
是的,我也试过用
levels(plot_df$levels) <- c("1", "2", "3", "4", "5")(和相反的顺序)改变因子水平顺序,但它不会改变图形顺序 -
还添加了数据示例
-
plot_df %>% mutate(levels = factor(levels, levels = 5:1)) %>% 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