ggplot2:将p值添加到图表中

14

我得到了这个图

在此输入图片描述

使用以下代码

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值,类似于这个问题的答案。

有没有更快或更自动化的方法来做到这一点?例如与添加R2值的方式类似。

更新

我所说的p值是斜率p值。当p < 0.005时,趋势被认为是高度统计显著的。


这不是这个问题的重复吗?它基本上告诉你要使用summarize() - Manuel R
请参考ggpmisc包的作者在ggplot2:在图表上添加回归线方程和R2问题的答案以获取更多详细信息,或联系作者。 - Uwe
你看过 stat_fit_glance 吗?来源:https://cran.r-project.org/web/packages/ggpmisc/vignettes/examples.html - bVa
1
p值并不意味着“每个趋势与零显著不同的概率”。 - C8H10N4O2
1个回答

24

使用 R 语言中的 ggpmisc 包中的 stat_fit_glance 函数。该包是 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基本上可以处理和使用ggplot2在R中传递的任何东西。用户指南介绍了一些像stat_fit_glance这样的函数: https://cran.r-project.org/web/packages/ggpmisc/vignettes/user-guide.html。此外,我认为这会给出模型p值,而不是斜率p值(一般情况下),对于多元线性回归,它们应该是不同的。然而,对于简单线性回归,它们应该是相同的。

这是绘制的图:

enter image description here


非常感谢您的时间和帮助。在我的分析中,斜率P值与模型P值不同。 - shiny
1
提醒一下,您的软件包名称中有一个拼写错误。应该是 ggpmisc 而不是 ggmisc。祝好 :) - J.Con
1
如果我从问题中复制并粘贴数据和公式以及答案中的ggplot,我会收到Warning: Ignoring unknown parameters: label.x.npc, label.y.npcError: Discrete value supplied to continuous scale的警告。 - CrunchyTopping
1
@CrunchyTopping label.x.npclabel.y.npc 都已被弃用。我建议使用 label.xlabel.y,同时您可能需要创建一个 my.formula <- y~x 并将其替换为 formula = formulaformula = my.formula,这样应该可以解决问题。 - Lime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接