You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggpubr为箱线图添加均值及p值标签的技术问询

Adding Mean Values & Paired T-Test P-Values to Faceted Boxplots with ggpubr

Hey there! Your approach to using ggpubr for this task is totally on the right track. Let me share a polished version of your code that ensures each facet shows the correct paired t-test p-value, plus tweaks to make the labels look clean and unobscured:

library(ggplot2)
library(ggpubr)

# Optional: Verify your paired t-test results first to cross-check the plot labels
compare_means(len ~ supp, data = ToothGrowth, method="t.test", paired=TRUE, group.by = "dose")

# Build the faceted boxplot with mean points
p1 <- ggboxplot(ToothGrowth, 
                x = "supp", 
                y = "len", 
                xlab = FALSE, 
                color = "supp", 
                palette = "jco", 
                facet.by = "dose", 
                add = "mean",  # Adds mean markers to each boxplot
                short.panel.labs = FALSE)

# Add paired t-test p-value labels, optimized for position
p2 <- p1 + 
  stat_compare_means(method = "t.test", 
                     paired = TRUE, 
                     label = "p.format",  # Shows "p=0.02" instead of just "p" for clarity
                     label.x = 1.5,  # Centers label between the two boxplots in each facet
                     label.y = max(ToothGrowth$len) * 1.05)  # Places label just above the tallest boxplot

p2

Key Notes & Fixes:

  • Swapped label = "p" for label = "p.format" to display full, readable p-value text (e.g., p=0.004) instead of just the letter "p". If you prefer just the numeric value, use label = "p.value" instead.
  • Added label.x and label.y to manually position the p-value labels—this prevents them from overlapping with boxplots or mean points, which is a common issue with faceted plots.
  • Since you're using facet.by = "dose", stat_compare_means() automatically runs the paired test within each dose group, so no extra group.by parameter is needed (though you can add it explicitly if you want to be extra clear).

If your original code had issues with p-values not showing up or being hidden, the position adjustments are almost certainly the fix. This version will give you clean, informative faceted boxplots with both mean markers and accurate paired t-test labels.

内容的提问来源于stack exchange,提问作者mercury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:40:21