gpt4 book ai didi

r - 反向堆积条形图

转载 作者:行者123 更新时间:2023-12-03 10:36:13 24 4
gpt4 key购买 nike

我正在使用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")

最佳答案

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

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

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

关于r - 反向堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42710056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com