R语言堆叠条形图内添加数值标签问题及ggplot2实现咨询
问题解决:水平堆叠条形图的数值标签放置(Base R + ggplot2)
数据准备
先定义矩阵与分类名称:
tabl <- matrix(c(3.89, 4.97, 8.56, 7.17, 35.67, 42.73, 51.68, 50.09, 48.30, 43.48, 34.95, 38.24, 12.14, 8.82, 4.81, 4.50), nrow = 4, byrow = TRUE) nombres_comp <- c("Tac. \n Urb", "Ven. \n Urb", "Tac. \n Game", "Ven. \n Game")
Base R 解决方案
原代码的核心问题是数值标签的坐标计算错误,水平堆叠条形图的分段中点需要基于累积和推导,而非直接使用barplot()返回的条形位置。修改后代码如下:
# 绘制堆叠条形图,保存条形的y轴位置(注意转置矩阵,barplot默认按列堆叠) bp <- barplot(t(tabl), main = NULL, xlab = "(%)", ylab = NULL, axes = TRUE, horiz = TRUE, beside = FALSE, names.arg = nombres_comp, col = c("#487c82","#487c83", "#81e0eb", "#b1ecf2")) # 计算每个分段的累积和,再推导中点位置(累积和减去当前值的一半) cum_sum <- apply(t(tabl), 2, cumsum) mid_points <- cum_sum - t(tabl)/2 # 在分段内部放置数值标签,优化显示效果 text(x = mid_points, y = bp, labels = round(t(tabl), 2), cex = 0.8, col = "white")
ggplot2 解决方案
ggplot2通过长格式数据可以更便捷实现需求,无需手动计算坐标:
library(ggplot2) library(tidyr) library(dplyr) # 将宽格式矩阵转换为ggplot2所需的长格式 tabl_df <- as.data.frame(tabl) %>% mutate(category = nombres_comp) %>% pivot_longer(-category, names_to = "segment", values_to = "value") # 绘制堆叠条形图并自动放置中心标签 ggplot(tabl_df, aes(x = value, y = category, fill = segment)) + geom_col(position = "stack") + geom_text(aes(label = round(value, 2)), position = position_stack(vjust = 0.5), size = 3, color = "white") + labs(x = "(%)", y = NULL) + scale_fill_manual(values = c("#487c82","#487c83", "#81e0eb", "#b1ecf2")) + theme_minimal()
内容的提问来源于stack exchange,提问作者John M. Riveros
相关产品推荐
相关产品推荐

