R语言双组前后测半小提琴图需求:分组配色与双侧分布展示
解决方案
你遇到的灰色小提琴问题是因为代码里硬编码了fill="gray",覆盖了aes(fill = group)的映射。要实现左右两侧分别显示对照组(红色)和处理组(蓝色)的半小提琴,完全可行,具体调整如下:
必要前提
确保已安装并加载ggplot2和see包(geom_half_violin来自see包):
install.packages(c("ggplot2", "see")) library(ggplot2) library(see)
修正后的完整代码
# 整理示例数据(若你的数据已存为s2可跳过此步) s2 <- data.frame( student_id = c(145, 145, 109, 109), group = factor(c("Treatment", "Treatment", "Control", "Control")), test_id = factor(c("pre", "post", "pre", "post")), Score = c(0.12, 0.78, 0.45, 0.99) ) # 绘图代码 p <- ggplot(s2, aes(x = test_id, y = Score)) + # 左侧添加对照组半小提琴(红色) geom_half_violin( data = subset(s2, group == "Control"), aes(fill = group), side = "left", trim = FALSE ) + # 右侧添加处理组半小提琴(蓝色) geom_half_violin( data = subset(s2, group == "Treatment"), aes(fill = group), side = "right", trim = FALSE ) + # 添加箱线图并调整位置避免重叠 geom_boxplot(width = 0.1, position = position_dodge(0.2)) + # 设置自定义颜色映射 scale_fill_manual(values = c("Control" = "red", "Treatment" = "blue")) + labs(title = "Half Violin", x = "Test", y = "Score") + theme_classic() + # 保持x轴顺序为pre、post(如需反转可保留scale_x_discrete(limits = rev)) scale_x_discrete(limits = c("pre", "post")) p
关键调整说明
- 移除硬编码fill:删掉原代码中
geom_violinhalf里的fill="gray",让fill由group映射控制。 - 分两组绘制半小提琴:通过
subset()分别筛选对照组和处理组数据,用side参数指定左侧/右侧显示。 - 自定义颜色映射:用
scale_fill_manual将对照组设为红色、处理组设为蓝色,确保颜色对应正确。 - 箱线图位置调整:添加
position = position_dodge(0.2)让箱线图和半小提琴位置对齐,避免重叠。
内容的提问来源于stack exchange,提问作者TheGeekGreek
相关产品推荐
相关产品推荐

