[DEPRECATED] stat_cor_r2

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)
  
Default is to add 
R<sup><font size = 1>2</font></sup> and <em>p</em>-value to the top-left
Default is to add R2 and p-value to the top-left
  
# 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)

  
Move to top-right quadrant and change R<sup><font size = 1>2</font></sup> significant figures to three.
Move to top-right quadrant and change R2 significant figures to three.
  
# 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)