使用ggpubr添加统计检验括号时提示'supp对象未找到'错误的解决方法
问题原因
基础箱线图p的全局美学映射(aes)中包含了fill=supp,而geom_bracket调用的compare_means返回结果里没有supp列。ggplot会自动继承全局美学映射,因此渲染geom_bracket时会尝试从它的数据源中查找supp,最终触发"object 'supp' not found"错误。
解决方法
以下两种方案均可解决该问题:
方案1:调整全局美学映射,仅在需要的图层中设置fill
将fill=supp从全局aes移至geom_boxplot和geom_point图层中,避免geom_bracket继承不必要的美学映射:
library(ggpubr) data("ToothGrowth") ToothGrowth$dose <- as.factor(ToothGrowth$dose) # 全局仅保留x、y映射,fill仅在需要的图层中定义 p <- ggplot(ToothGrowth, aes(x = dose, y = len)) + geom_boxplot(aes(fill=supp), width=0.8,lwd=0.7, alpha=0.6, outlier.color="black", outlier.size=1) + geom_point(shape=21, aes(fill=supp), size=1, position=position_dodge(width=0.8)) # 预先生成统计检验结果 stat_res <- compare_means(len~supp, group.by="dose", data=ToothGrowth) %>% mutate(dose=factor(dose)) # 添加统计检验括号 p + geom_bracket(aes(label=p.format, xmin=dose, xmax=dose), y.position=max(ToothGrowth$len) * 1.05, bracket.shorten=0.4, data=stat_res)
方案2:关闭geom_bracket的美学映射继承
在geom_bracket中添加inherit.aes=FALSE参数,明确告知ggplot不继承全局的美学映射:
library(ggpubr) data("ToothGrowth") ToothGrowth$dose <- as.factor(ToothGrowth$dose) p <- ggplot(ToothGrowth, aes( x = dose, y = len, fill=supp )) + geom_boxplot(width=0.8,lwd=0.7, alpha=0.6, outlier.color="black", outlier.size=1) + geom_point(shape=21, aes(fill=supp), size=1, position=position_dodge(width=0.8)) stat_res <- compare_means(len~supp, group.by="dose", data=ToothGrowth) %>% mutate(dose=factor(dose)) # 关闭继承,避免查找supp列 p + geom_bracket(aes(label=p.format, xmin=dose, xmax=dose), y.position=max(ToothGrowth$len) * 1.05, bracket.shorten=0.4, data=stat_res, inherit.aes=FALSE)
内容的提问来源于stack exchange,提问作者Elizabeth Wallace
相关产品推荐
相关产品推荐

