如何在带P值的分组柱状图中添加对齐的数据点?
问题:分组柱状图数据点与柱状条无法对齐
使用ggpubr包绘制带P值的分组柱状图时,添加geom_point()后发现数据点无法和对应的柱状条对齐,出现错位情况。
原代码如下:
library(ggpubr) library(rstatix) #data df <- ToothGrowth df$dose <- as.factor(df$dose) head(df, 3) #pvalue stat.test <- df %>% group_by(dose) %>% t_test(len ~ supp) %>% adjust_pvalue(method = "bonferroni") %>% add_significance("p.adj") stat.test # Create a bar plot with error bars (mean +/- sd) bp <- ggbarplot( df, x = "dose", y = "len", add = "mean_sd", color= "supp", palette = c("#00AFBB", "#E7B800"), position = position_dodge(0.8) ) + geom_point() # Add p-values onto the bar plots stat.test <- stat.test %>% add_xy_position(fun = "mean_sd", x = "dose", dodge = 0.8) bp + stat_pvalue_manual( stat.test, label = "p.adj.signif", tip.length = 0.01 ) # Move down the brackets using `bracket.nudge.y` bp + stat_pvalue_manual( stat.test, label = "p.adj.signif", tip.length = 0, bracket.nudge.y = -2 )
解决方法
错位的核心原因是geom_point()未设置与柱状条一致的分组偏移参数。只需给geom_point()添加position = position_dodge(0.8),和ggbarplot中position参数的dodge值保持一致即可。
修正后的关键代码片段
bp <- ggbarplot( df, x = "dose", y = "len", add = "mean_sd", color= "supp", palette = c("#00AFBB", "#E7B800"), position = position_dodge(0.8) ) + geom_point(position = position_dodge(0.8)) # 此处添加position参数
完整修正代码
library(ggpubr) library(rstatix) #data df <- ToothGrowth df$dose <- as.factor(df$dose) head(df, 3) #pvalue stat.test <- df %>% group_by(dose) %>% t_test(len ~ supp) %>% adjust_pvalue(method = "bonferroni") %>% add_significance("p.adj") stat.test # Create a bar plot with error bars (mean +/- sd) bp <- ggbarplot( df, x = "dose", y = "len", add = "mean_sd", color= "supp", palette = c("#00AFBB", "#E7B800"), position = position_dodge(0.8) ) + geom_point(position = position_dodge(0.8)) # 修正处 # Add p-values onto the bar plots stat.test <- stat.test %>% add_xy_position(fun = "mean_sd", x = "dose", dodge = 0.8) bp + stat_pvalue_manual( stat.test, label = "p.adj.signif", tip.length = 0.01 ) # Move down the brackets using `bracket.nudge.y` bp + stat_pvalue_manual( stat.test, label = "p.adj.signif", tip.length = 0, bracket.nudge.y = -2 )
设置后,数据点会和对应的分组柱状条精准对齐。
内容的提问来源于stack exchange,提问作者Trinh Phan-Canh
相关产品推荐
相关产品推荐

