ggplot2堆叠柱状图搭配帕累托线时geom_text()标签顺序颠倒求助
问题原因
堆叠柱状图的geom_text标签顺序颠倒,核心是geom_text未声明与geom_bar一致的分组映射,导致堆叠计算时的组排序和柱子实际堆叠顺序不匹配。
解决方法
- 优先补全geom_text的分组映射,在aes中加入和geom_bar一致的
fill = alvor参数,让文本知道按对应分组堆叠:
ggplot() + theme_mso() + geom_bar(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor), stat = "identity") + # 补全fill=alvor映射 geom_text(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor, label = n), position = position_stack(vjust = .5)) + scale_fill_manual(values = col) + geom_point(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret)) + geom_line(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, group = 1), stat = "identity") + scale_y_continuous(sec.axis = sec_axis(~(./total_value)*100, name = "Procent")) + geom_text(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, label = procent), position = position_stack(vjust= 1.08))
- 如果补全映射后标签仍然颠倒,给
position_stack添加reverse = TRUE参数手动对齐顺序:
geom_text(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor, label = n), position = position_stack(vjust = .5, reverse = TRUE))
- 若要从根源避免顺序错乱,可主动指定fill变量的因子顺序,明确堆叠逻辑:
# 按你需要的从下到上的堆叠顺序设置levels uth.sum$alvor <- factor(uth.sum$alvor, levels = c("最低层类别", "中间层类别", "最高层类别"))
内容的提问来源于stack exchange,提问作者Sejersboll
相关产品推荐
相关产品推荐

