【问题标题】:ggplot2: add p-values to the plotggplot2:将 p 值添加到绘图中
【发布时间】:2016-09-28 22:47:33
【问题描述】:

我得到了这个情节

使用下面的代码

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 时,趋势被认为具有高度统计显着性。

【问题讨论】:

标签: r ggplot2 p-value


【解决方案1】:

使用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_glance:https://cran.r-project.org/web/packages/ggpmisc/vignettes/user-guide.html。我也相信这给出了模型 p 值,而不是斜率 p 值(通常),这对于多元线性回归会有所不同。但是对于简单的线性回归,它们应该是相同的。

剧情如下:

【讨论】:

  • 非常感谢您的时间和帮助。在我的分析中,斜率 p 值与模型 p 值不同。
  • 仅供参考,您的包名中有错字。它应该是ggpmisc,而不是ggmisc。干杯:)
  • 如果我复制并粘贴问题中的数据和公式以及答案中的ggplot,我会得到Warning: Ignoring unknown parameters: label.x.npc, label.y.npcError: Discrete value supplied to continuous scale
  • @CrunchyTopping label.x.npclabel.y.npc 都已被弃用。我建议使用label.xlabel.y,您也可以创建一个my.formula &lt;- y~x 并将其替换为formula = formulaformula = my.formula,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 2014-12-21
  • 2018-05-11
相关资源
最近更新 更多