Created
October 2, 2018 10:17
-
-
Save arcaravaggi/b2c9bf65d4df24b5f030c8062695bbd8 to your computer and use it in GitHub Desktop.
Label ggplot facet plots with facet group name and R^2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From https://stackoverflow.com/questions/17022553/adding-r2-on-graph-with-facets | |
# Function for calculating R^2 | |
# Adjust the lm call as required | |
lm_eqn = function(df){ | |
m = lm(min_t ~ max_t, df); | |
eq <- substitute(r2, | |
list(r2 = format(summary(m)$r.squared, digits = 3))) | |
as.character(as.expression(eq)); | |
} | |
# Create dataframe containing the R^2, species and a facet label | |
# Adjust the column names and paste details, as required | |
eqns <- by(pdat, pdat$code, lm_eqn) | |
df2 <- data.frame(eq = unclass(eqns), species = names(eqns)) | |
df2$lab = paste(df2$species, "R^2 =", df2$eq, sep=" ") | |
# Make a labeling function that will refer to your data frame of labels | |
r2_labeller <- function(variable,value){ | |
return(df2$lab) | |
} | |
# Add the labeller function to facet_wrap | |
facet_wrap( ~ code, ncol=2, scales = "free", labeller = r2_labeller) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment