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

使用factor()作为X轴时,ggplot箱线图Dodge功能失效问题求助

问题

希望绘制分组箱线图,让每个strength强度值对应的True Positives(TP)和False Positives(FP)箱线图并排显示,但使用position_dodge()后未达到预期效果,生成的图混乱。询问position_dodge()未生效的原因。

现有代码

ggplot(data, aes(x = factor(strength))) +
  geom_boxplot(aes(y = TP, fill = "TP"), position = position_dodge(width = 0.8)) +
  geom_boxplot(aes(y = FP, fill = "FP"), position = position_dodge(width = 0.8)) +
  scale_fill_manual(values = c("TP" = "blue", "FP" = "red")) +
  labs(title = "Count",
       x = "Strength", y = "Count")

示例数据集

trialstrengthFPTP
1-356
1267
1121
2-234
2244
2322

原因分析与解决方案

未生效的核心原因

  • 你当前通过两次调用geom_boxplot()分别绘制TP和FP的箱线图,这会生成两个独立的图层。position_dodge()仅对同一图层内的分组元素生效,无法跨图层协调位置,导致两个图层的箱线图重叠,显示混乱。
  • 现有数据是宽格式(TP、FP作为独立列),而ggplot2绘制分组箱线图的标准要求是长格式数据(将类别(TP/FP)合并为一列,对应数值单独列为一列)。

正确实现步骤

  1. 转换数据格式:使用tidyr::pivot_longer()将宽格式数据转为长格式,把TP和FP合并为type列,对应数值存入count列。
  2. 单图层绘制:在同一个geom_boxplot()中,通过fill = type指定分组,此时position_dodge()会自动对同一x轴分组下的不同type元素进行位置偏移。

修正后的代码

library(tidyr)
library(ggplot2)

# 转换为长格式数据
data_long <- pivot_longer(data, cols = c(FP, TP), names_to = "type", values_to = "count")

# 绘制分组箱线图
ggplot(data_long, aes(x = factor(strength), y = count, fill = type)) +
  geom_boxplot(position = position_dodge(width = 0.8)) +
  scale_fill_manual(values = c("TP" = "blue", "FP" = "red")) +
  labs(title = "Count",
       x = "Strength", y = "Count")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:55:26