R语言ggline设置numeric.x.axis后stat_compare_means报错求助
问题:ggline数值型X轴搭配stat_compare_means报错解决
问题场景
使用ggpubr的ggline绘制带统计检验的图形时,不设置numeric.x.axis = TRUE(X轴为离散型)代码能正常运行:
data("ToothGrowth") library(ggplot2) library(ggpubr) ggline(ToothGrowth, x = "dose", y = "len", add = "mean_se", color = "supp", palette = "jco") + stat_compare_means(aes(group = supp), label = "p.signif", label.y = c(16, 25, 29))
但开启numeric.x.axis = TRUE将X轴转为数值型后,运行以下代码报错:
ggline(ToothGrowth, x = "dose", y = "len", add = "mean_se", color = "supp", palette = "jco", numeric.x.axis = TRUE) + stat_compare_means(aes(group = supp), label = "p.signif", label.y = c(16, 25, 29))
报错信息:
Computation failed in
stat_compare_means(): '*.npc coord for x axis should be either a numeric value in [0-1] or a character strings including one of right, left, center, centre, middle
解决方法
当X轴为连续数值型时,stat_compare_means无法自动识别离散分组的X位置,需要手动指定比较的X坐标或调整位置对齐方式,以下两种方案都可行:
方案1:指定每个比较组的X轴数值位置
直接给每个dose对应的比较标签指定X轴数值(可轻微偏移避免重叠):
ggline(ToothGrowth, x = "dose", y = "len", add = "mean_se", color = "supp", palette = "jco", numeric.x.axis = TRUE) + stat_compare_means(aes(group = supp), label = "p.signif", x = c(0.5, 1.0, 2.0), # 对应dose的三个数值 label.y = c(16, 25, 29))
方案2:使用position_dodge对齐分组位置
通过position_dodge让统计标签与分组线条对齐,无需手动指定X值:
ggline(ToothGrowth, x = "dose", y = "len", add = "mean_se", color = "supp", palette = "jco", numeric.x.axis = TRUE) + stat_compare_means(aes(group = supp), label = "p.signif", position = position_dodge(width = 0.2), # 调整宽度适配分组间距 label.y = c(16, 25, 29))
原理说明
X轴转为连续型后,stat_compare_means默认的离散分组位置计算逻辑失效,必须明确指定X坐标或通过位置调整函数对齐分组,避免npc坐标解析错误。
内容的提问来源于stack exchange,提问作者Janine Lux
相关产品推荐
相关产品推荐

