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

ggplot堆叠条形图:隐藏计数<5的数据标签及条纹图案实现

解决两个ggplot图表优化问题

1. 隐藏计数小于5的数据标签

直接在geom_text的label参数里用ifelse做判断,把计数小于5的标签设为空字符串即可,无需额外过滤数据框:

geom_text(stat = 'count', aes(label = ifelse(..count.. >= 5, ..count.., '')), 
          position = position_stack(vjust = 0.5))

原理很简单:当stat='count'计算出的..count..小于5时,标签内容为空,自然不会显示,同时所有条形都能保留。

2. 让pattern='stripe'生效

ggplot2原生不支持填充图案,得借助ggpattern包的geom_bar_pattern替换默认的geom_bar,具体步骤:

  • 先安装并加载ggpattern包
  • 把geom_bar替换为geom_bar_pattern,同时设置图案相关参数(比如条纹颜色、密度等)

修改后的完整代码

library(tidyverse)
library(ggpattern) # 新增加载图案包

custom_colors <- c("grey", "darkgrey")
df %>%
  ggplot(aes(x = fct_infreq(job), fill = comms)) +
  theme(text=element_text(size=10, family="Times New Roman"))+
  # 替换为带图案的条形函数,设置条纹样式
  geom_bar_pattern(position = "stack", 
                   pattern = 'stripe', # 指定条纹图案
                   pattern_fill = "black", # 条纹颜色
                   pattern_density = 0.1, # 条纹密度
                   pattern_spacing = 0.02) # 条纹间距
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
        legend.position='bottom',
        panel.background = element_blank(),
        panel.grid.major = element_blank(),   
        panel.grid.minor = element_blank())+
  labs(title = "", x="Job Title", y="Number of Participants (n)", fill='')+
  # 过滤小计数标签
  geom_text(stat = 'count', aes(label = ifelse(..count.. >=5, ..count.., '')), 
            position = position_stack(vjust = 0.5))+
  scale_fill_manual(values = custom_colors)

如果需要给不同comms分组设置不同图案,可以把pattern = comms放到aes里,再用scale_pattern_manual指定对应图案:

ggplot(aes(x = fct_infreq(job), fill = comms, pattern = comms)) +
  # ...其他代码不变
  scale_pattern_manual(values = c("stripe", "none")) # 给不同分组分配图案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:32:59