NOTE (2023-10-17): To add R2 and p-values to ggplots, I recommend using the function stat_poly_eq() from the package ggpmisc instead. stat_cor_r2() will be removed from this site shortly.
A function modified from the stat_cor() function in ggpubr to add the R2 value and p-value to ggplot for a linear model.
Requires the packages ggplot2, ggpubr, and finalfit.
Load Function into Global Environment
source("https://lauralogozzo.github.io/assets/stat_cor_r2.R.txt")
Documentation
stat_cor_r2(
mapping = NULL,
data = NULL,
label.x.npc = "left",
label.y.npc = "top",
output.type = "expression",
digits = 2,
r.digits = digits,
p.digits = digits,
geom = "text",
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
...
)
See documentation for stat_cor() from ggpubr.
Examples
# Load required packages
library("ggplot2")
library("ggpubr")
library("finalfit")
# Load iris data
data(iris)
# Plot scatterplot and add r2 and p-value
ggplot(data = iris, aes(x = Sepal.Length, y = Petal.Length)) +
geom_point(size = 2) +
geom_smooth(method = "lm") +
theme_classic(base_size = 14) +
stat_cor_r2(size = 5)
# Load ggplot
library("ggplot2")
library("ggpubr")
library("finalfit")
# Get iris data
data(iris)
# Ggplot example
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(size = 2) +
geom_smooth(method = "lm") +
theme_classic(base_size = 14) +
stat_cor_r2(size = 6, label.x.npc = "center", r.digits = 3)
# Load ggplot
library("ggplot2")
library("ggpubr")
library("finalfit")
# Get iris data
data(iris)
# Ggplot example
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point(size = 2) +
geom_smooth(method = "lm", se = F) +
theme_classic(base_size = 14) +
stat_cor_r2(size = 5, label.x.npc = "center", show.legend = F)