如何在分组箱线图上叠加可区分测试分组的散点图?
问题:如何在分组箱线图上区分两次测试的散点
我想要创建一个简单图表,对比不同班级及两次测试(first/second)的成绩。已使用以下R代码绘制出按Class和Test分组的箱线图:
a <- data.frame(Name = rep(c("A", "B", "C", "D", "E", "F", "G", "H", "I"),2), Class = rep(c(rep("class1",3), rep("class2", 3), rep("class3", 3)),2), Test = c(rep("first",9), rep("second", 9)), Score = c(80, 70, 50, 60, 80, 90, 75, 85, 50, 75, 85, 98, 85, 76, 50, 75, 68, 72) ) g <- ggplot(a, aes(x = Class, y = Score, fill = Test))+ geom_boxplot()
该代码生成了符合预期的分组箱线图。随后我尝试叠加散点图:
g <- g + geom_point()
但生成的散点图中,同一班级的两次测试成绩散点重合,无法区分。请问如何像箱线图一样区分first和second测试的散点?
解决方案
方法一:用position_dodge让散点与箱线对齐错开
箱线图默认通过position_dodge实现分组左右错开,给散点图层添加相同参数,就能让不同Test的散点和对应箱线对齐,避免重合:
g <- ggplot(a, aes(x = Class, y = Score, fill = Test)) + geom_boxplot() + # 匹配箱线的错开宽度,同时用color区分测试组 geom_point(position = position_dodge(width = 0.75), aes(color = Test))
方法二:结合geom_jitter避免同组内散点重叠
如果同一测试组内有重复成绩,散点仍会重合,这时可以用geom_jitter给散点添加轻微抖动,同时保留分组错开效果:
g <- ggplot(a, aes(x = Class, y = Score, fill = Test)) + geom_boxplot() + geom_jitter( position = position_dodge(width = 0.75), aes(color = Test), size = 2, # 调整点的大小 alpha = 0.8 # 调整透明度,减少重叠遮挡 )
内容的提问来源于stack exchange,提问作者矢坂 健
相关产品推荐
相关产品推荐

