geom_text显示各数据点标签而非总计的问题求助
ggplot2 geom_text 未显示总计数据标签的问题排查与解决
你在使用ggplot2绘制堆叠柱形图时,geom_text没有按预期显示每个选项的总计占比标签,反而显示了每个交叉细分数据点的重叠标签。从截图能看到每个柱子里有多个重复标签,问题出在数据处理逻辑和图层映射上。
问题根源
- 原代码先对三个变量做交叉计数(
count(invest_reward, more_support, pay_fee)),随后计算的pct = n/sum(n)是全局占比(所有交叉组合的总和为分母),而非每个问题下各选项的占比。 - 转为长格式后仅用
group_by(name)分组,但未重新计算分组内的占比,导致每个细分行都带着全局占比值,geom_text会为每个细分绘制标签,最终出现重叠。
解决方案
调整数据处理流程,先转长格式再按问题+选项分组计数,计算分组内的占比;同时修正geom_text的映射逻辑,确保显示每个柱子的总计标签。
修改后的代码
incentive_select %>% select(invest_reward, more_support, pay_fee) %>% # 先转长格式,避免生成交叉细分数据 pivot_longer(cols = c(invest_reward, more_support, pay_fee), names_to = "name", values_to = "value") %>% # 按问题和选项分组统计数量 count(name, value = factor(value)) %>% # 计算每个问题下各选项的占比 group_by(name) %>% mutate(pct = n/sum(n)) %>% # 重命名问题名称 mutate(name = case_when( name == "invest_reward" ~ "Only people who are investing in rooftop solar panels \nshould be rewarded for their contribution to clean energy generation", name == "more_support" ~ "More support should be provided to those who don’t have\naccess to rooftop solar", name == "pay_fee" ~ "Incentives are too high for rooftop solar panels owners.\nThey should pay a fee for sending power to the grid" )) %>% ggplot(aes(x = value, y = pct, fill = name, label = scales::percent(pct)))+ geom_col() + facet_wrap(~name, ncol = 1) + # 标签显示在柱子顶部(如需内部居中,改用position_stack(vjust = 0.5)) geom_text(vjust = -0.5, size = 3, color = "black") + scale_y_continuous(labels = scales::percent, expand = expansion(mult = c(0, 0.1))) + scale_x_discrete(labels = label_wrap_gen(width = 25, multi_line = TRUE)) + labs(y = "Percentage", title = "How strongly do you agree with the proposed rooftop solar incentive reforms in your local jurisdiction?") + theme(axis.title.x=element_blank(), axis.text.x = element_text(vjust = 0.5, hjust=1), legend.position = "bottom")
关键修改点
- 先转长格式再计数,避免生成不必要的交叉细分数据。
- 按
name分组后重新计算占比,确保是每个问题下各选项的相对占比。 - 调整
geom_text位置:顶部显示用vjust=-0.5,内部居中用position_stack(vjust=0.5),按需选择。 - 给Y轴添加
expand参数,避免顶部标签被图表边界截断。
内容的提问来源于stack exchange,提问作者H B
相关产品推荐
相关产品推荐

