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

如何在ggplot2的geom_bar中仅展示count>10的统计条形?

解决方案:在ggplot2中筛选count>10的条形

你可以通过两种方式在ggplot函数内实现仅保留count>10的条形:

方法1:在统计层直接过滤

利用after_stat()获取stat="count"计算出的数量值,给geom_bar和stat_count添加filter参数筛选符合条件的类别:

ggplot(r_df, aes(spice, colour="black", fill = "orange")) +
  geom_bar(stat = "count", filter = after_stat(count) > 10) + 
  stat_count(geom = "text", colour = "black", size = 3.,
             aes(label = after_stat(count)), position=position_stack(vjust=1.05),
             filter = after_stat(count) > 10) +
  theme(axis.text.x = element_text(angle=90, vjust=.6))

这里的filter = after_stat(count) > 10会在统计完每个类别的数量后,仅保留数量大于10的条目,同时文本标签也会同步过滤,不会显示被移除的类别。

方法2:在ggplot内部先汇总过滤数据

另一种更直观的方式是在ggplot的data参数里,用dplyr完成计数和过滤,后续直接用geom_col绘制(因为已经有预计算的数量):

ggplot(r_df %>% 
         dplyr::count(spice) %>% 
         dplyr::filter(n > 10), 
       aes(spice, n, colour="black", fill = "orange")) +
  geom_col() + 
  geom_text(aes(label = n), colour = "black", size = 3.,
            position=position_stack(vjust=1.05)) +
  theme(axis.text.x = element_text(angle=90, vjust=.6))

这种方式提前完成了数据汇总和筛选,绘图逻辑更清晰,也避免了重复统计。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:55:16