R ggplot2条形图含负值时数值标签位置错位问题如何解决
解决方法
你遇到的标签错位问题核心是固定hjust参数无法同时适配正负两种方向的条形,单组条形图额外加position_dodge2也会引入不必要的位置偏移,按如下方法修改即可:
- 移除
geom_text中多余的position_dodge2参数,该参数仅用于多组需要错开排列的条形图,你的场景不需要 - 将hjust参数改为根据数值正负动态取值,正向条形用hjust=0让标签左对齐贴在条形右端,负向条形用hjust=1让标签右对齐贴在条形左端
- 可以用
nudge_x动态调整标签和条形的间距,数值可根据你的显示需求自行调整
修改后的核心代码(仅调整geom_text部分)
ggplot(USA, aes(x = Values, y = fct_reorder(factor(Categories), Values), fill = Categories)) + scale_fill_manual(values = colors) + geom_col(width = 0.65) + # 仅修改geom_text部分即可 geom_text(aes(label = paste0(round(Values/1000000, 2), " mil t"), hjust = I(ifelse(Values > 0, 0, 1))), size = 3.3, nudge_x = ifelse(USA$Values > 0, 1.5e7, -1.5e7)) + labs(title = "Greenhouse gas emissions by sector, United States 2016") + scale_y_discrete(expand = expansion(mult = c(0.05, 0.05))) + scale_x_continuous(breaks = c(0, 100000000, 300000000, 500000000, 1000000000, 1500000000, 2000000000), labels = c("0", "100 mil", "300 mil", "500 mil", "1 bilion", "1.5 bilion", "2 bilion"), expand = expansion(mult = c(0.15, 0.15))) + theme(legend.position = "none", axis.title = element_blank(), panel.grid = element_blank(), panel.background = element_blank(), axis.ticks.y = element_blank(), axis.text.y = element_text(family = "sans", size = 9), title = element_text(size = 11, family = "sans", face = "bold"))
如果你坚持使用ggfittext方案,修改geom_bar_text参数即可
添加place = "outside"参数让标签显示在条形外侧,直接传入size参数控制文字大小:
geom_bar_text(place = "outside", size = 3.3, padding.x = unit(1, "mm"))
padding.x参数可以调整标签和条形之间的间距,可根据需求调整数值。
内容的提问来源于stack exchange,提问作者epku
相关产品推荐
相关产品推荐

