在R中使用ggplot绘制堆叠条形图并添加条形标签
堆叠条形图添加标签解决方案
数据子集
years <- c(2015, 2019, 2020, 2021, 2021, 2022) Points <- c(7, 26, 9, 18, 28, 12) Design <- c("Standard 2019", "Standard 2019", "Standard 2019", "Standard 2019", "LCT 2021", "LCT 2021") PointSummary <- data.frame(years, Points, Design)
需求与当前代码
需要创建堆叠条形图展示各年份、各设计类型的采样点数,目标为堆叠样式的条形图,当前用于添加标签的geom_text代码如下:
library(ggplot2) ggplot(data = PointSummary, aes(x = years, y = Points, fill = Design)) + geom_bar() + geom_text(position = position_stack(vjust = 1.6), color = "white", size = 6)
修正方案
当前代码存在两处关键问题,调整后即可得到正确的带标签堆叠条形图:
geom_bar默认统计计数,需指定stat="identity"直接使用已有数值绘制条形geom_text需明确指定标签内容,并调整位置参数让标签显示在条形内部合适位置
修正后的完整代码:
library(ggplot2) ggplot(data = PointSummary, aes(x = factor(years), y = Points, fill = Design)) + geom_bar(stat = "identity") + geom_text(aes(label = Points), position = position_stack(vjust = 0.5), color = "white", size = 6) + labs(x = "年份") # 可选:将x轴标签改为中文
关键调整说明
x = factor(years):将年份转为离散类别,避免被当作连续数值处理stat = "identity":告知ggplot直接使用y轴的Points数值绘制条形aes(label = Points):指定标签显示内容为采样点数position_stack(vjust = 0.5):让标签位于每个堆叠分段的垂直中心,可根据需求微调vjust值调整位置
内容的提问来源于stack exchange,提问作者DrewB31
相关产品推荐
相关产品推荐

