使用geom_boxplot生成柱状而非箱线图的问题排查
为什么ggplot2绘制箱线图时显示为柱状图?
问题描述
我用以下代码尝试为数据集test2绘制箱线图,但输出的却是类似柱状图的图形:
ggplot(test2, aes(x=GameCondition, y=Alignment.bin, fill = GameCondition)) + geom_boxplot()
但使用测试数据集test运行完全相同的代码却能生成正常的箱线图:
test <- data.frame(GameCondition = c("a", "a", "b", "b", "b", "c", "c", "c"), Alignment.bin = c(1, 0, 1, 0, 1,0, 1,NA)) test$GameCondition <- as.factor(test$GameCondition)
两个数据集的GameCondition均为因子(factor)类型,Alignment.bin均为双精度(dbl)类型,请问这是怎么回事?
核心原因
你的test2里,Alignment.bin本质是二元分类变量(只有0和1两个取值),且每个GameCondition分组的取值分布极度集中:要么全是0、要么全是1,要么两者的数量没有足够差异支撑箱线图的五数概括(最小值、第一四分位数、中位数、第三四分位数、最大值)。
当箱线图的统计指标被压缩到两个离散值时,视觉上就会变成类似柱状的形态:
- 若某个分组所有值都是0,箱线图的箱体、须线会完全重合,呈现为一条线或“柱子”;
- 若分组里只有0和1,中位数、Q1、Q3都会贴近这两个值,箱体被压缩成窄带,加上须线后看起来和柱状图无异。
而测试数据集test的分组中,0和1的分布更分散(比如组b有2个1、1个0),箱线图的统计特征能正常展示,所以是标准的箱线图样式。
验证方法
你可以先检查test2的分组取值分布,确认上述推测:
# 查看每个分组的0/1计数 table(test2$GameCondition, test2$Alignment.bin) # 查看每个分组的五数概括 aggregate(Alignment.bin ~ GameCondition, data = test2, summary)
解决办法
如果想更清晰展示二元变量的分布,建议换用更适合的图形:
- 分组频率柱状图:直接展示每个分组中0和1的数量/占比
ggplot(test2, aes(x=GameCondition, fill = factor(Alignment.bin))) + geom_bar(position = "dodge") + labs(fill = "Alignment.bin") - 箱线图叠加散点:保留箱线图的同时,用散点展示原始数据分布
ggplot(test2, aes(x=GameCondition, y=Alignment.bin, fill = GameCondition)) + geom_boxplot(width = 0.5) + geom_jitter(width = 0.2, alpha = 0.5)
内容的提问来源于stack exchange,提问作者Icewaffle
相关产品推荐
相关产品推荐

