首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggplot2:将p值添加到绘图中

ggplot2:将p值添加到绘图中
EN

Stack Overflow用户
提问于 2016-05-31 04:41:19
回答 1查看 28.8K关注 0票数 14

我有个阴谋

使用下面的代码

代码语言:javascript
复制
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时,这一趋势被认为具有高度的统计学意义。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-08 17:11:06

使用stat_fit_glance,它是R中ggpmisc包的一部分,这个包是ggplot2的扩展,所以它与它很好地配合。

代码语言:javascript
复制
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值(一般情况下),这对于多元线性回归是不同的。但是,对于简单的线性回归,它们应该是相同的。

情节如下:

票数 23
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37536950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档