ggplot2:在图中添加p值

问题描述 投票:11回答:1

我有这个情节

enter image description here

使用下面的代码

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)

除了R2,我还想在方面添加p值。我可以通过首先运行回归然后获取p值并使用geom_text()来添加这些p值来手动执行此操作similar to the answer of this question.

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

更新

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

r ggplot2 p-value
1个回答
15
投票

使用stat_fit_glance,它是R中ggpmisc包的一部分。这个包是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)

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

这是情节:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.