使用ggplot2+gghalves+ggdist绘制Raincloud图数据显示异常求助
解决Raincloud图重绘时数据点随机异常的问题
问题根源
- 错误的颜色映射:
geom_half_point中colour = "Summary statistics"被放在aes()内部,ggplot会将该字符串视为分类变量进行映射,而非直接设置颜色,导致数据点被错误分组,出现随机偏移的异常值。 - 未定义的数据集引用:
lims(y = range(seconddataun$avg_uniq_comp))引用了未提供的seconddataun数据集,若该数据集范围与当前使用的data差异较大,会放大异常点的视觉效果。 - 比例尺顺序冲突:
scale_color_pilot()与scale_color_manual()的顺序错误,手动颜色设置未正确覆盖默认比例尺,加剧了颜色映射的混乱。
修正后的代码
# 基于当前数据集计算y轴范围 y_range <- range(data$avg_uniq_comp) uniquecompplot <- ggplot(data, aes(x = hollow_breeder_status, y = avg_uniq_comp, fill = hollow_breeder_status)) + # 修正:将颜色设置移出aes,作为固定参数 gghalves::geom_half_point(aes(shape = as.factor(nobroods)), colour = "black", side = "l", range_scale = 0.05, alpha = .6, size = 2.2, position = position_identity()) + ggdist::stat_halfeye( adjust = .4, width = .87, colour = NA) + labs(title = "Breeder status' relationship to unique competitors per day", subtitle = "Summary statistics: general linear model results over raw data", x = "Breeder status", y = "Average unique competitors per day") + coord_flip() + pilot::scale_fill_pilot() + pilot::theme_pilot(grid = "", axes = "b") + theme(legend.position = "bottom", axis.text.y = element_text(face = "italic"), plot.title = element_text(size = 16), plot.subtitle = element_text(size = 12)) + scale_shape_manual(name = "Number of broods", values = c("1" = 16, "2" = 17, "3" = 15, "4" = 8)) + guides(fill = FALSE) + # 修正:使用当前数据集的y轴范围 lims(y = y_range) uniquecompplot
关键修改说明
- 颜色设置修正:将颜色参数从
aes()中移出,作为图层固定属性,避免ggplot将其解析为变量映射,彻底解决数据点随机偏移问题。 - y轴范围修正:基于当前绘图数据集计算y轴范围,确保轴范围与数据匹配,消除异常点被过度放大的视觉效果。
- 比例尺冲突解决:移除重复的颜色比例尺设置,仅保留填充色的pilot比例尺,简化设置并避免映射冲突。
内容的提问来源于stack exchange,提问作者flatcrab
相关产品推荐
相关产品推荐

