使用 ToothGrowth 数据集(内置于 R 中),我使用了以下代码。
library(ggplot2)
library(tidyverse)
library(ggpubr)
p <- ggboxplot(ToothGrowth, x = "supp", y = "len",
color = "supp", palette = "jco",
add = "jitter",
facet.by = "dose", short.panel.labs = FALSE)
p + stat_compare_means(label = "p.format")
Run Code Online (Sandbox Code Playgroud)
现在,我希望 p 值有 4 位数字。我研究了以前的类似帖子,然后尝试了以下两个选项
p + stat_compare_means(label = "p.format", digits = 4)
p + stat_compare_means(label = "p.format", round(p.format, 4))
Run Code Online (Sandbox Code Playgroud)
不幸的是,两者都不起作用。可能有人有解决方案吗?谢谢你。
这是一种使用的选项sprintf
library(ggplot2)
library(tidyverse)
library(ggpubr)
p <- ggboxplot(ToothGrowth, x = "supp", y = "len",
color = "supp", palette = "jco",
add = "jitter",
facet.by = "dose", short.panel.labs = FALSE)
p + stat_compare_means(aes(label = sprintf("p = %5.4f", as.numeric(..p.format..))))
Run Code Online (Sandbox Code Playgroud)
针对您的评论,您可以执行以下操作
p <- ggboxplot(ToothGrowth, x = "supp", y = "len",
color = "supp", palette = "jco",
add = "jitter",
facet.by = "dose", short.panel.labs = FALSE)
p + stat_compare_means(aes(label = ifelse(
p < 1.e-2,
sprintf("p = %2.1e", as.numeric(..p.format..)),
sprintf("p = %5.4f", as.numeric(..p.format..)))))
Run Code Online (Sandbox Code Playgroud)
在这里,我使用科学记数法将 p 值打印p < 1.e-2为 4 位浮点数。