Home > front end >  R stat_compare_means - 3 decimals and p < 0.001 and "p" in italics
R stat_compare_means - 3 decimals and p < 0.001 and "p" in italics

Time:09-13

I want to add p values to a ggplot. They should have three 3 decimals and if p < 0.001 then it should display that ("p < 0.001"). And the "p" should be in italics. Somehow one has to do it with sprintf but how exactly?

library(ggplot2)
library(tidyverse)
library(ggpubr)

ggboxplot(ToothGrowth, x = "dose", y = "len") 
stat_compare_means(label = "p.format")

CodePudding user response:

One option would be to create the label via ?plotmath notation to italicize the p, set argument parse=TRUE (which via ... is passed to geom_text) and use scales::label_pvalue to format the p-value:

library(ggplot2)
library(ggpubr)

ggboxplot(ToothGrowth, x = "dose", y = "len")  
  stat_compare_means(aes(
    label = paste0(
      "italic(p)",
      scales::label_pvalue()(..p..)
    )
  ),
  parse = TRUE
  )

  • Related