R箱形图,使用“ stat_compare_means”更改p值中的位数

时间:2019-05-09 23:35:17

标签: r boxplot p-value

使用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")

现在,我希望p值具有4位数字。我研究了以前的类似帖子,然后尝试了以下两个选项

p + stat_compare_means(label = "p.format", digits = 4)
p + stat_compare_means(label = "p.format", round(p.format, 4))

不幸的是,两者都不起作用。有人可以解决吗?谢谢。

1 个答案:

答案 0 :(得分:1)

这是使用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..))))

enter image description here


更新

针对您的评论,您可以执行以下操作

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..)))))

enter image description here

如果p < 1.e-2以外的其他4个数字为浮点数,则使用科学计数法打印p值。