问题描述
我想在散点图中添加一个 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)
我们也可以实现斜体的p like this:
ggplot(mtcars,method="lm") +
(geom="text",label=paste0("italic('p')~'='",parse=T,size=8)
但是请注意,我们丢失了剥离的零(前导零又回来了,而我们不想要它)。知道如何解决这个问题吗?