如何在ggplot2::facet_wrap中添加inc标签并避免重叠及调整位置
问题描述
在ggplot2::facet_wrap中添加inc(同比增长率)标签时,用geom_text(aes(label = scales::percent(inc,0.1)),hjust=2,vjust=12)实现了标签显示,但出现了标签重叠问题。希望将类别B的75%标签移至红色柱子(2023年对应柱子)内部。
原始代码如下:
library(tidyverse) plot_data <- data.frame(category=c('A','A','B','B'), period=c('2022','2023','2022','2023'), sales=c(10,12,0.2,0.35)) plot_data %>% group_by(category) %>% mutate(inc = sales/lag(sales)-1) %>% ggplot(aes(x=category,y=sales,fill=period))+geom_col(position=position_dodge(0.8))+ geom_text(aes(label = sales),position = position_dodge2(0.8))+ geom_text(aes(label = scales::percent(inc,0.1)),hjust=2,vjust=12)+ facet_wrap(~ category,scales="free")
解决方案
1. 先过滤无效标签
inc是同比增长率,只有2023年的数据有计算结果,2022年的inc为NA,直接过滤掉这些无效行,避免多余标签干扰:
filter(!is.na(inc))
2. 让标签和柱子对齐
用position_dodge(0.8)和柱子的偏移量保持一致,确保标签对应到2023年的红色柱子,再调整vjust让标签落在柱子内部:
3. 优化可读性(可选)
给柱子内的标签设置白色字体,同时把销售额标签移到柱子上方,避免冲突。
完整修改后的代码:
library(tidyverse) plot_data <- data.frame(category=c('A','A','B','B'), period=c('2022','2023','2022','2023'), sales=c(10,12,0.2,0.35)) plot_data %>% group_by(category) %>% mutate(inc = sales/lag(sales)-1) %>% filter(!is.na(inc)) %>% ggplot(aes(x=category,y=sales,fill=period))+ geom_col(position=position_dodge(0.8))+ geom_text(aes(label = sales),position = position_dodge2(0.8), vjust = -0.5)+ geom_text(aes(label = scales::percent(inc,0.1)), position = position_dodge(0.8), vjust = 1.5, color = "white")+ facet_wrap(~ category,scales="free")
精细调整(可选)
如果不同类别柱子高度差异大,可针对单个类别微调位置:
geom_text(aes(label = scales::percent(inc,0.1)), position = position_dodge(0.8), vjust = ifelse(category == "B", 1.2, 1.5), color = "white")
内容的提问来源于stack exchange,提问作者anderwyang
相关产品推荐
相关产品推荐

