Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R boxplot, change number of digits in p value using "stat_compare_means"

Tags:

Using the ToothGrowth dataset (built into R), I have used the following code.

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

Now, I would like the p values to have 4 digits. I researched previous similar posts and then tried the following two options

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

Unfortunately, neither worked. Might anybody have a solution? Thank you.

like image 760
Sylvia Rodriguez Avatar asked May 09 '19 23:05

Sylvia Rodriguez


1 Answers

Here is one option using 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


Update

In response to your comment, you could do the following

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

Here I print the p-value using scientific notation if p < 1.e-2 else as a float with 4 digits.

like image 99
Maurits Evers Avatar answered Sep 25 '22 02:09

Maurits Evers