如何在 ggplot2 `annotate()` - APA 风格中格式化 p 值?

问题描述

我想在散点图中添加一个 p 值,同时尊重 APA style。这需要两个元素:(a) 斜体 p,和 (b) 去除前导零(但也:将小于 .001 的值格式化为

我们可以使用自定义公式去除前导零

# Formatting formula
format.p <- function(p,precision = 0.001) {
  digits <- -log(precision,base = 10)
  p <- formatC(p,format = 'f',digits = digits)
  p[p == formatC(0,digits = digits)] <- paste0('< ',precision)
  sub("0","",p)}

# Get p-value
(p = cor.test(mtcars$wt,mtcars$mpg)$p.value)
1.293959e-10

# Format p-value
(p = format.p(p))
"< .001"

# Make plot    
library(ggplot2)
ggplot(mtcars,aes(x=wt,y=mpg)) +
  stat_smooth(geom="line",method="lm")+
  annotate(geom="text",label=paste0("p = ",p),x=4.5,y=25,size=8)

enter image description here

我们也可以实现斜体的p like this:

ggplot(mtcars,method="lm") +

(geom="text",label=paste0("italic('p')~'='",parse=T,size=8)

enter image description here

但是请注意,我们丢失了剥离的零(前导零又回来了,而我们不想要它)。知道如何解决这个问题吗?

解决方法

@rawr 在评论中提供的解决方案(谢谢!)

关键是将 label=paste0("italic('p')~'='",p) 改为 label=sprintf("italic('p')~'%s'",p)

此外,为了避免出现函数同时输出等于和小于符号的情况(例如,p = < .001),我还修改了 format.p() 函数以选择 {{1} } 或 < 视情况而定。

这是最终的解决方案:

=

enter image description here