GGPlot2技术问题:如何在堆叠条形图分段中显示名称与数量
为堆叠条形图的分段添加国家名称和数量标签
你已经实现了按年份统计的堆叠条形图,要给每个分段添加对应国家名称和数量,核心是先统计各分组的计数,再计算标签的垂直位置,最后用geom_text添加标签。具体实现如下:
步骤1:预处理数据,统计分组计数与标签位置
先使用dplyr包(需提前安装加载)统计每个年份-国家组合的数量,并计算每个分段的垂直居中位置,确保标签落在分段中间:
library(dplyr) # 统计各年份-国家的数量,计算标签垂直居中位置 dataframe_summary <- dataframe %>% count(date, country, name = "count") %>% group_by(date) %>% mutate(y_pos = cumsum(count) - count/2)
步骤2:修改ggplot代码,插入标签
基于汇总后的数据绘制条形图,并用geom_text添加包含国家名称和数量的标签:
# 基于汇总数据绘图,geom_bar使用stat="identity" plot <- ggplot(dataframe_summary, aes(x = as.character(date), y = count, fill = country)) plot <- plot + geom_bar(stat = "identity", width = 0.5) plot <- plot + scale_fill_manual(values = additional_column_summary_scale) plot <- plot + scale_x_discrete(limits=lims, labels=lims, breaks=lims) # 添加标签:换行显示国家名称和数量,调整文本大小避免重叠 plot <- plot + geom_text(aes(y = y_pos, label = paste(country, count, sep = "\n")), size = 4, color = "black") # 保留原主题与标签设置 plot <- plot + theme(text = element_text(size = 15), axis.title.x = element_text(vjust=-0.5), plot.title = element_text(size = 17, hjust = 0.5), axis.text.y = element_text(size = 10), axis.text.x = element_text(angle = 90, size = 10, vjust = 0.5), panel.spacing.x = unit(5, "lines"), panel.border = element_blank(), axis.line = element_line(size = 0.1), panel.background = element_rect(fill = "white")) + labs(y = "Number of Sequences", x = "Date", title=paste("Number of Sequence by Year and ", trimws("Country", which = c("left")))) + scale_y_continuous(expand = c(0,0)) ggsave("plot.png", height=7, width=10)
关键细节说明
y_pos = cumsum(count) - count/2:通过累加当前及之前分段的总高度,减去当前分段高度的一半,得到分段的垂直中心位置,保证标签居中显示。paste(country, count, sep = "\n"):让国家名称和数量换行展示,避免标签过长导致重叠。- 若后续数据量较大,可调整
geom_text的size参数,或添加check_overlap = TRUE自动隐藏重叠标签。
内容的提问来源于stack exchange,提问作者Yasir
相关产品推荐
相关产品推荐

