R ggplot多分组柱状图顶部数据标签显示异常问题求助
问题根因
标签错位是两个原因导致的:
- 原代码中x轴映射为连续日期类型,两个日期间隔接近3个月,ggplot默认的分组闪避宽度基于x轴数值间隔计算,手动设置的0.9闪避宽度和柱子实际闪避宽度不匹配
- 没有明确给
geom_bar设置统一的闪避宽度,导致文本和柱子的闪避规则不一致
修正方案
将x轴转为离散因子类型(更符合两个季度对比的展示场景),同时统一柱子和文本的闪避宽度,修正后完整代码如下:
# 加载依赖包 library(ggplot2) library(dplyr) # 数据构造逻辑保持不变 Date <- as.Date(c("2020-10-01","2020-10-01","2020-10-01","2020-10-01", "2020-10-01","2020-10-01","2020-10-01","2020-10-01","2020-10-01", "2020-10-01","2020-10-01","2020-10-01","2020-10-01","2020-10-01", "2021-01-01","2021-01-01","2021-01-01","2021-01-01","2021-01-01", "2021-01-01","2021-01-01","2021-01-01","2021-01-01","2021-01-01", "2021-01-01","2021-01-01","2021-01-01","2021-01-01")) GEO <- c( "Canada","Newfoundland and Labrador","Prince Edward Island", "Nova Scotia","New Brunswick","Quebec","Ontario","Manitoba","Saskatchewan", "Alberta","British Columbia","Yukon","Northwest Territories","Nunavut", "Canada","Newfoundland and Labrador","Prince Edward Island","Nova Scotia", "New Brunswick","Quebec","Ontario","Manitoba","Saskatchewan","Alberta", "British Columbia","Yukon","Northwest Territories","Nunavut") JVR <- c(3.5,2.6,3.2,3.3,3.9,4.1,3.4,3.1,2.3,2.4,4.2,4.4,3.0,2.6, 3.6,2.0,2.5,3.2,3.2,4.2,3.3,3.1,2.7,2.8,4.5,4.7,4.2,3.6) df <- data.frame(Date=as.Date(Date),GEO=GEO,JVR=JVR) # 修正后绘图代码 ggplot(filter(df,Date>=as.Date("2020-10-01")), aes(x=as.factor(Date),y=JVR,fill=GEO)) + geom_bar(stat="identity",position=position_dodge(width=0.9)) + geom_text(aes(label=JVR),position=position_dodge(width=0.9), vjust=-0.3,size=3) + labs(x="季度")
如果需要保留x轴为日期格式,不需要转因子,只需要把geom_text的position_dodge(width=0.9)调整为position_dodge(width=20)即可对齐。
内容的提问来源于stack exchange,提问作者Phil Smith
相关产品推荐
相关产品推荐

