Skip to content

Instantly share code, notes, and snippets.

@jasper1918
Created March 21, 2017 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasper1918/07f13190c62f3c6e4b4b2823f499d134 to your computer and use it in GitHub Desktop.
Save jasper1918/07f13190c62f3c6e4b4b2823f499d134 to your computer and use it in GitHub Desktop.
ggplot_linearity
# ggplot with equation
lm_eqn <- function(df, key_y, key_x){
m<-lm(formula(paste(key_y,"~",key_x)), df)
eq <- substitute(italic(y) == b %.% italic(x) + a*","~~italic(R)^2~"="~r2,
list(a = formatC(coef(m)[1], digits = 4,format="f", flag="#"),
b = formatC(coef(m)[2], digits = 4,format = "f", flag="#"),
r2 = formatC(summary(m)$r.squared, digits = 4,format = "f", flag="#")))
as.character(as.expression(eq))
}
ggplot_linearity<-function(df, key_x, key_y, plot_xlab="", plot_ylab=""){
all <- ggplot(df, aes_string(key_x, key_y)) +
geom_boxplot(aes_string(group = key_x)) +
geom_point(size=2, color="black", alpha=.6, shape=17) +
geom_smooth(aes(colour = "black"), method='lm', alpha=.2) +
scale_x_continuous(breaks = round(seq(5, 100, by = 5),1)) +
scale_y_continuous() +
xlab(plot_xlab) + ylab(plot_ylab) +
theme_bw() +
theme(text = element_text(size=20)) +
theme(legend.position="none")
all
final_plot <- all + geom_text(x=max(df[key_x]/1.75),y=max(df[key_y]/5),
label = lm_eqn(df, key_y, key_x),size=6, parse = TRUE)
return(final_plot)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment