You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2绘制条形图时geom_text()出现重复重叠标签如何解决

问题原因

你的原始数据集在同一个veryHealthy分组下存在多条重复记录,geom_text会默认对每一行数据都生成一个文本标签,完全重叠的多个标签堆叠后就会呈现出类似黑色线条的效果。

解决方法

你只需要在调用geom_text时传入去重后的数据集即可,不需要修改其他绘图逻辑,修改后代码如下:

library(ggplot2)
library(dplyr)

ggplot(foods, aes(x=veryHealthy, y=diary, width=healthy , fill = dairyFree)) + 
  geom_bar(stat='identity') +
  scale_x_discrete(expand = c(0, 0)) +
  facet_grid(~veryHealthy, scales = "free", space = "free") +
  # 仅对去重后的数据绘制文本标签
  geom_text(data = ~distinct(.x, veryHealthy, .keep_all = TRUE),
            aes(label = percent), position = position_stack(0.5))

如果不想加载dplyr,也可以用base R的unique函数实现去重:

geom_text(data = unique(foods[,c("veryHealthy","percent","diary")]),
          aes(label = percent), position = position_stack(0.5))

补充说明

因为你的数据集里每个veryHealthy分组对应的percent、diary等值完全一致,去重后每个分组仅保留1条有效记录,就可以避免重复绘制标签的问题,同时不会影响标签的位置和数值准确性。

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:54:02