ggplot2:在图中添加p值

shi*_*iny 12 r ggplot2 p-value

我有这个情节

在此输入图像描述

使用下面的代码

library(dplyr) 
library(ggplot2)
library(ggpmisc)

df <- diamonds %>%
  dplyr::filter(cut%in%c("Fair","Ideal")) %>%
  dplyr::filter(clarity%in%c("I1" ,  "SI2" , "SI1" , "VS2" , "VS1",  "VVS2")) %>%
  dplyr::mutate(new_price = ifelse(cut == "Fair", 
                                   price* 0.5, 
                                   price * 1.1))

formula <- y ~ x    
ggplot(df, aes(x= new_price, y= carat, color = cut)) +
  geom_point(alpha = 0.3) +
  facet_wrap(~clarity, scales = "free_y") +
  geom_smooth(method = "lm", formula = formula, se = F) +
  stat_poly_eq(aes(label = paste(..rr.label..)), 
               label.x.npc = "right", label.y.npc = 0.15,
               formula = formula, parse = TRUE, size = 3)
Run Code Online (Sandbox Code Playgroud)

除了R2,我还想在方面添加p值.我可以通过首先运行回归然后获取p值并使用geom_text()添加这些p值手动执行此操作,类似于此问题的答案.

有没有更快或自动化的方法呢?例如,类似于添加R2值的方式.

更新

我正在谈论的p值是斜率p值.当p <0.005时,趋势被认为是高度统计学上显着的.

aka*_*h87 16

使用stat_fit_glance它是ggpmiscR中包的一部分.这个包是一个扩展,ggplot2所以它适用于它.

ggplot(df, aes(x= new_price, y= carat, color = cut)) +
       geom_point(alpha = 0.3) +
       facet_wrap(~clarity, scales = "free_y") +
       geom_smooth(method = "lm", formula = formula, se = F) +
       stat_poly_eq(aes(label = paste(..rr.label..)), 
       label.x.npc = "right", label.y.npc = 0.15,
       formula = formula, parse = TRUE, size = 3)+
       stat_fit_glance(method = 'lm',
                       method.args = list(formula = formula),
                       geom = 'text',
                       aes(label = paste("P-value = ", signif(..p.value.., digits = 4), sep = "")),
       label.x.npc = 'right', label.y.npc = 0.35, size = 3)
Run Code Online (Sandbox Code Playgroud)

stat_fit_glance基本上lm()在R中传递任何东西并允许它使用处理和打印ggplot2.用户指南包含一些功能的概要,例如stat_fit_glance:https://cran.r-project.org/web/packages/ggpmisc/vignettes/user-guide.html.另外我认为这给出了模型p值,而不是斜率p值(通常),这对于多元线性回归是不同的.对于简单的线性回归,它们应该是相同的.

这是情节:

在此输入图像描述