我正在使用ggplot创建堆积的条形图,如下所示:
plot_df <- df[!is.na(df$levels), ]
ggplot(plot_df, aes(group)) + geom_bar(aes(fill = levels), position = "fill")
这给了我这样的东西:
在此处输入图片说明
如何颠倒堆叠条形图本身的顺序,以使级别1在每个条形图的底部,而级别5在每个条形图的顶部?
我已经看到了很多问题(例如,如何使用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")
慕婉清6462132
慕田峪9158850