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

1

6

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.

Sitka answered 9/5, 2019 at 23:35 Comment(2)
Where are ggboxplot and stat_compare_means from? Always explicitly include any library calls to external non-base R packages.Electromotor
@MauritsEvers Apologies for that. I added them above. Hope that helps? Thank you.Sitka
E
6

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.

Electromotor answered 10/5, 2019 at 1:46 Comment(5)
Thank you. That is terrific, exactly what I was looking for. Unfortunately, however, I am applying this to a large dataset and some p values are for example 2.3e-08. Is there a way to change p=0.023 to p=0.0230, as per above, but also leave p=2.3e-08 as it is? Sorry for the extra trouble. Thank you.Sitka
@SylviaRodriguez Sure that's possible, please see my update above.Electromotor
Wonderful! Thank you, Maurits. This is exactly what I hoped for.Sitka
I am really sorry. I have another issue. Some of my p values are "<2e-16". If I use this code, they show up as "NA" instead of as "<2e-16". Any chance you can solve this too, please? Thank you.Sitka
Oh, I solved it myself: p + stat_compare_means(aes(label = ifelse( p < 2.e-16, p.format, ifelse( p < 1.e-2, sprintf("p = %2.1e", as.numeric(..p.format..)), sprintf("p = %5.4f", as.numeric(..p.format..))))))Sitka

© 2022 - 2024 — McMap. All rights reserved.