ggplot2: add p-values to the plot

前端 未结 1 619
天命终不由人
天命终不由人 2020-12-14 22:02

I got this plot

Using the code below

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

df <- diamonds %>%
  dplyr::filter(cut%in%c(\         


        
相关标签:
1条回答
  • 2020-12-14 22:56

    Use stat_fit_glance which is part of the ggpmisc package in R. This package is an extension of ggplot2 so it works well with it.

    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 basically takes anything passed through lm() in R and allows it to processed and printed using ggplot2. The user-guide has the rundown of some of the functions like stat_fit_glance: https://cran.r-project.org/web/packages/ggpmisc/vignettes/user-guide.html. Also I believe this gives model p-value, not slope p-value (in general), which would be different for multiple linear regression. For simple linear regression they should be the same though.

    Here is the plot:

    0 讨论(0)
提交回复
热议问题