LHAndersen
LHAndersen

Reputation: 121

Add p-value to ggplot without creating a lm-obejct separately

I have to create a large (100+) number of ggplots of linear models. I would like to add the p-value (and potentially R2) to each plot. I know it is possible to do this using ggpmisc. Here, I employ stat_fit_glance to add the p-value. My 'problem' is that both of these require me to run lm first to be inserted as formula = my_lm.

As I have to create a large number of plots, I was wondering if there is a way to avoid creating the lm object first, and simply have it calculated while producing the ggplot? I can do it for t-tests for boxplots using stat_compare_means, and really hope to find a way to do it with lm's as well.

My code is present below. I would like to be able to skip the first line of code:

my_lm <- lm(y ~ x)


ggplot(data = complete, aes(x= x, y = y))+  
geom_point()+
theme_classic()+
geom_smooth(method = "lm")+
labs(x="Ellenberg F", y = "Species richness")+
stat_fit_glance(method = 'lm',
              method.args = list(data = complete, formula = my_lm),
              geom = 'text',
              aes(label = paste("p-value = ", signif(..p.value.., digits = 4), sep = "")),
              label.x = 8.5, label.y = 25, size = 3)

I have tried simply putting formula = y ~ x with no luck.

Upvotes: 1

Views: 2018

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24262

From the help of ggpmisc::stat_fit_glance: method.args = list(formula = y ~ x).
This means that you don't need to run an lm first.
You can only specify the formula for the linear model.

library(ggpmisc)
set.seed(1)
n <- 100
x <- 8+rnorm(n)
y <- 11+x+2*rnorm(n)
complete <- data.frame(x, y)

summary(lm(y~x))
ggplot(data = complete, aes(x= x, y = y))+  
geom_point()+
theme_classic()+
geom_smooth(method = "lm")+
labs(x="Ellenberg F", y = "Species richness")+
stat_fit_glance(method = 'lm',
       method.args = list(formula = y ~ x),  geom = 'text', 
       aes(label = paste("p-value=", signif(..p.value.., digits = 4), 
                      "   R-squared=", signif(..r.squared.., digits = 3), sep = "")),
       label.x = 8.5, label.y = 25, size = 5)

enter image description here

Upvotes: 2

Related Questions