Here are two methods for displaying the fit equation and R squared on each facet of a grid of plots
library(ggplot2)
library(dplyr)
set.seed(6734)
#make a toy data set
x <- seq(0,9)
y1 <- seq(0,9) + rnorm(10)
y2 <- seq(0,9) + rnorm(10, 0,2)
y3 <- seq(0,9) + rnorm(10, 0, 3)
y4 <- seq(0,9) + rnorm(10, 0 ,4)
df <- data.frame(Population = rep(c("A", "B", "C", "D"), each = 10),
x= rep(x,4), y = c(y1,y2, y3, y4), stringsAsFactors = FALSE)
#Add fit equations to each facet
#Define a function returning a string representation of the fit result
#FIT$coeff[1] is the intercept
#FIT$coeff[2] is the slope
#signif(x, n) returns x rounded to n significant digits
GetEq <- function(xcol, ycol) {
FIT <- lm( ycol ~ xcol)
if(FIT$coeff[1] >= 0) {
paste0( "y = ", signif(FIT$coeff[2],4), "x + ", signif(FIT$coeff[1],4), "\n",
"R sqr = ", round(summary(FIT)$r.squared, 4))
} else {
paste0( "y = ", signif(FIT$coeff[2],4), "x - ", abs(signif(FIT$coeff[1],4)), "\n",
"R sqr = ", round(summary(FIT)$r.squared,4 ))
}
}
#apply GetEq to each subset of df
Eqs <- df %>% group_by(Population) %>%
summarize(Form = GetEq( x, y))
#Method 1 use geom_text to print the fit equation on each facet
#provide x and y locations for placing the equations.
EqsXY <- mutate(Eqs, x = 2.5, y = 10)
#Plot the data and use EqsXY as the data for geom_text()
ggplot(df, aes(x,y)) + geom_point() + geom_smooth(method = "lm", se = FALSE) +
geom_text(mapping = aes(x, y, label = Form), data = EqsXY) +
facet_wrap(~Population)
#Method 2: Use the labeller of facet_wrap to put the fit equation and R^2 in
#the facet title
Labels <- paste0(Eqs$Population, ": ", Eqs$Form)
ggplot(df, aes(x,y)) + geom_point() + geom_smooth(method = "lm", se = FALSE) +
facet_wrap(~Population,
labeller = as_labeller(setNames(Labels, Eqs$Population)))