R boxplot,使用“stat_compare_means”更改p值中的位数

Syl*_*uez 5 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")
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)

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

Mau*_*ers 5

这是一种使用的选项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 位浮点数。

  • @SylviaRodriguez 当然这是可能的,请参阅上面我的更新。 (2认同)
  • 哦,我自己解决了: p + stat_compare_means(aes(label = ifelse( p &lt; 2.e-16, p.format, ifelse( p &lt; 1.e-2, sprintf("p = %2.1e", as .nu​​meric(..p.format..)), sprintf("p = %5.4f", as.numeric(..p.format..)))))) (2认同)