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

如何在ggplot2箱线图中移除NA值?

解决ggplot箱线图无法去除NA值的问题

你的问题核心在于数据是rowwise_df格式——这种逐行分组的结构会干扰subset()、na.omit()这类函数的筛选逻辑,导致NA值无法被彻底过滤。另外你的数据中gender字段也存在NA值,之前的操作只针对sum_variable过滤,这也是无效行残留的原因之一。

解决步骤

  • 先取消数据的逐行分组结构,转换为普通数据格式
  • 同时过滤掉sum_variable和gender中的NA值

修正后的代码示例

方法1:先清理数据再绘图

# 取消逐行分组,转换为普通数据框
df <- df %>% ungroup()

# 过滤掉包含NA的行
clean_df <- df %>% filter(!is.na(sum_variable), !is.na(gender))

# 绘制箱线图
ggplot(clean_df, aes(x = gender, y = sum_variable, fill = gender)) +
  stat_boxplot(geom = "errorbar", width = 0.5) +
  geom_boxplot(fill = "lightblue") +  # 注意颜色名需统一为无空格格式
  stat_summary(fun = mean, geom = "point", shape = 10, size = 3.5, color = "black") +
  ggtitle("Title") +
  theme_bw() +
  theme(legend.position = "none")

方法2:在ggplot调用中直接链式处理数据

ggplot(df %>% ungroup() %>% drop_na(sum_variable, gender), 
       aes(x = gender, y = sum_variable, fill = gender)) +
  stat_boxplot(geom = "errorbar", width = 0.5) +
  geom_boxplot(fill = "lightblue") +
  stat_summary(fun = mean, geom = "point", shape = 10, size = 3.5, color = "black") +
  ggtitle("Title") +
  theme_bw() +
  theme(legend.position = "none")

额外注意点

  1. 原始代码中geom_boxplot(fill = "light blue")的空格会导致颜色识别错误,需改为lightblue
  2. stat_summary中的fun.y参数已被弃用,改用fun = mean更符合当前ggplot版本规范
  3. 同时过滤gender的NA值,可避免出现无数据的空箱线图类别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:35:16