如何在ggplot2的堆叠条形图中添加单个数值标签
嘿,这就帮你搞定在ggplot2堆叠条形图里加数值标签的问题!先把你的代码整理好,然后一步步来实现:
首先,先确认你的数据集M是正确的(我帮你补全了结构里的细节):
# Load the packages library(dplyr) library(readr) library(tidyr) library(ggplot2) library(RColorBrewer) # Create a data set called M M <- structure( list( X1 = c("Diversity", "Endangerment", "Marketability", "Total"), B1 = c(5.1, 4.9, 4.7, 4.6), B2 = c(3.5, 3, 3.2, 3.1), B3 = c(1.4, 1.4, 1.3, 1.5), B4 = c(7.1, 4.7, 3.2, 5.1) ), .Names = c("X1", "B1", "B2", "B3", "B4"), row.names = c(NA, -4L), class = "data.frame" )
第一步:把宽格式数据转成长格式
ggplot2做堆叠条形图需要长格式数据,用pivot_longer转换:
M_long <- M %>% pivot_longer(cols = -X1, names_to = "Category", values_to = "Value")
情况1:给每个堆叠块添加数值标签
如果想在每个堆叠的色块里显示对应的数值,用geom_text配合position_stack(vjust = 0.5)让标签居中:
ggplot(M_long, aes(x = X1, y = Value, fill = Category)) + geom_col() + # 标签放在每个堆叠块的中间位置 geom_text(aes(label = Value), position = position_stack(vjust = 0.5), size = 3) + scale_fill_brewer(palette = "Set2") + labs(title = "Stacked Bar Chart with Segment Labels", x = "Indicator", y = "Score") + theme_minimal()
情况2:给每个条形顶部添加总数值标签
如果想在每个条形的顶部显示该条形的总和,先计算每个X1的总得分,再添加标签:
# 先计算每个Indicator的总得分 M_totals <- M_long %>% group_by(X1) %>% summarise(Total_Score = sum(Value)) ggplot(M_long, aes(x = X1, y = Value, fill = Category)) + geom_col() + # 调用汇总数据,把总标签放在条形上方 geom_text( data = M_totals, aes(x = X1, y = Total_Score, label = Total_Score), vjust = -0.3, # 调整垂直位置,避免和条形重叠 size = 4, color = "#333333" ) + scale_fill_brewer(palette = "Set2") + labs(title = "Stacked Bar Chart with Total Labels", x = "Indicator", y = "Score") + theme_minimal() + # 扩展y轴上限,防止总标签被截断 ylim(0, max(M_totals$Total_Score) + 1)
这样两种需求都能满足啦,你可以根据自己的需要选其中一种~
内容的提问来源于stack exchange,提问作者Warwick Wainwright
相关产品推荐
相关产品推荐

