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

使用complete()与ggplot绘图时出现虚假计数为1的小柱状条问题

解决方法

问题根源在于complete(col1, col2)会生成所有col1与col2的组合,原本不存在的组合会新增空行,但geom_bar()默认会统计每行的数量,这些空行被误计为1条记录,因此出现高度为1的柱子。按以下方式修改即可解决:

  1. 先统计每个col1+col2组合的实际数量
  2. 用complete()补全所有组合,并将缺失组合的计数设为0
  3. 改用geom_col()直接使用已统计好的数值,避免自动计数

修改后的代码:

data <- data.frame("col1" = c("a", "b", "a", "c", "a", "b", "a", "c"),
                   "col2" = c("x", "y", "x", "y", "x", "y", "x", "y"))

data %>%
  count(col1, col2) %>%  # 统计每个组合的实际数量
  complete(col1, col2, fill = list(n = 0)) %>%  # 补全缺失组合,计数设为0
  ggplot(aes(x = col2, y = n)) +
  geom_col(aes(fill = col1),
           position = position_dodge(preserve = "single"))

修改后,计数为0的组合(x-b、x-c、y-a)不会显示柱子,同时能保持并列柱状图的位置一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:44:54